/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: 2011-12-31 20:07:11 UTC
  • mfrom: (535.1.9 wireless-network-hook)
  • Revision ID: teddy@recompile.se-20111231200711-6dli3r8drftem57r
Merge new wireless network hook.  Fix bridge network hook to use
hardware addresses instead of interface names.  Implement and document
new "CONNECT" environment variable for network hooks.

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-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
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,
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
90
90
#include <grp.h>                /* setgroups() */
91
 
#include <argz.h>               /* argz_add_sep(), argz_next(),
92
 
                                   argz_delete(), argz_append(),
93
 
                                   argz_stringify(), argz_add(),
94
 
                                   argz_count() */
95
 
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
96
 
                                   EAI_SYSTEM, gai_strerror() */
97
91
 
98
92
#ifdef __linux__
99
93
#include <sys/klog.h>           /* klogctl() */
141
135
static const char sys_class_net[] = "/sys/class/net";
142
136
char *connect_to = NULL;
143
137
const char *hookdir = HOOKDIR;
144
 
uid_t uid = 65534;
145
 
gid_t gid = 65534;
146
138
 
147
139
/* Doubly linked list that need to be circularly linked when used */
148
140
typedef struct server{
149
141
  const char *ip;
150
 
  in_port_t port;
 
142
  uint16_t port;
151
143
  AvahiIfIndex if_index;
152
144
  int af;
153
145
  struct timespec last_seen;
157
149
 
158
150
/* Used for passing in values through the Avahi callback functions */
159
151
typedef struct {
 
152
  AvahiSimplePoll *simple_poll;
160
153
  AvahiServer *server;
161
154
  gnutls_certificate_credentials_t cred;
162
155
  unsigned int dh_bits;
164
157
  const char *priority;
165
158
  gpgme_ctx_t ctx;
166
159
  server *current_server;
167
 
  char *interfaces;
168
 
  size_t interfaces_size;
169
160
} mandos_context;
170
161
 
171
 
/* global so signal handler can reach it*/
172
 
AvahiSimplePoll *simple_poll;
 
162
/* global context so signal handler can reach it*/
 
163
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
164
                      .dh_bits = 1024, .priority = "SECURE256"
 
165
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
166
                      .current_server = NULL };
173
167
 
174
168
sig_atomic_t quit_now = 0;
175
169
int signal_received = 0;
183
177
  perror(print_text);
184
178
}
185
179
 
186
 
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
180
__attribute__((format (gnu_printf, 2, 3)))
187
181
int fprintf_plus(FILE *stream, const char *format, ...){
188
182
  va_list ap;
189
183
  va_start (ap, format);
190
184
  
191
185
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
186
                             program_invocation_short_name));
193
 
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
187
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
188
}
195
189
 
196
190
/*
198
192
 * bytes. "buffer_capacity" is how much is currently allocated,
199
193
 * "buffer_length" is how much is already used.
200
194
 */
201
 
__attribute__((nonnull, warn_unused_result))
202
195
size_t incbuffer(char **buffer, size_t buffer_length,
203
196
                 size_t buffer_capacity){
204
197
  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;
 
198
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
199
    if(buffer == NULL){
211
200
      return 0;
212
201
    }
213
 
    *buffer = new_buf;
214
202
    buffer_capacity += BUFFER_SIZE;
215
203
  }
216
204
  return buffer_capacity;
217
205
}
218
206
 
219
207
/* 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){
 
208
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
209
                int af){
223
210
  int ret;
224
211
  server *new_server = malloc(sizeof(server));
225
212
  if(new_server == NULL){
234
221
    perror_plus("strdup");
235
222
    return false;
236
223
  }
237
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
238
 
  if(ret == -1){
239
 
    perror_plus("clock_gettime");
240
 
    return false;
241
 
  }
242
224
  /* Special case of first server */
243
 
  if(*current_server == NULL){
 
225
  if (mc.current_server == NULL){
244
226
    new_server->next = new_server;
245
227
    new_server->prev = new_server;
246
 
    *current_server = new_server;
 
228
    mc.current_server = new_server;
 
229
  /* Place the new server last in the list */
247
230
  } else {
248
 
    /* Place the new server last in the list */
249
 
    new_server->next = *current_server;
250
 
    new_server->prev = (*current_server)->prev;
 
231
    new_server->next = mc.current_server;
 
232
    new_server->prev = mc.current_server->prev;
251
233
    new_server->prev->next = new_server;
252
 
    (*current_server)->prev = new_server;
 
234
    mc.current_server->prev = new_server;
 
235
  }
 
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
237
  if(ret == -1){
 
238
    perror_plus("clock_gettime");
 
239
    return false;
253
240
  }
254
241
  return true;
255
242
}
257
244
/* 
258
245
 * Initialize GPGME.
259
246
 */
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){
 
247
static bool init_gpgme(const char *seckey, const char *pubkey,
 
248
                       const char *tempdir){
265
249
  gpgme_error_t rc;
266
250
  gpgme_engine_info_t engine_info;
267
251
  
 
252
  
268
253
  /*
269
254
   * Helper function to insert pub and seckey to the engine keyring.
270
255
   */
271
 
  bool import_key(const char * const filename){
 
256
  bool import_key(const char *filename){
272
257
    int ret;
273
258
    int fd;
274
259
    gpgme_data_t pgp_data;
286
271
      return false;
287
272
    }
288
273
    
289
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
290
275
    if(rc != GPG_ERR_NO_ERROR){
291
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
292
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
336
321
  }
337
322
  
338
323
  /* Create new GPGME "context" */
339
 
  rc = gpgme_new(&(mc->ctx));
 
324
  rc = gpgme_new(&(mc.ctx));
340
325
  if(rc != GPG_ERR_NO_ERROR){
341
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
342
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
355
340
 * Decrypt OpenPGP data.
356
341
 * Returns -1 on error
357
342
 */
358
 
__attribute__((nonnull, warn_unused_result))
359
343
static ssize_t pgp_packet_decrypt(const char *cryptotext,
360
344
                                  size_t crypto_size,
361
 
                                  char **plaintext,
362
 
                                  mandos_context *mc){
 
345
                                  char **plaintext){
363
346
  gpgme_data_t dh_crypto, dh_plain;
364
347
  gpgme_error_t rc;
365
348
  ssize_t ret;
391
374
  
392
375
  /* Decrypt data from the cryptotext data buffer to the plaintext
393
376
     data buffer */
394
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
395
378
  if(rc != GPG_ERR_NO_ERROR){
396
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
397
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
398
381
    plaintext_length = -1;
399
382
    if(debug){
400
383
      gpgme_decrypt_result_t result;
401
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
384
      result = gpgme_op_decrypt_result(mc.ctx);
402
385
      if(result == NULL){
403
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
404
387
      } else {
481
464
  return plaintext_length;
482
465
}
483
466
 
484
 
__attribute__((warn_unused_result))
485
 
static const char *safer_gnutls_strerror(int value){
486
 
  const char *ret = gnutls_strerror(value);
 
467
static const char * safer_gnutls_strerror(int value){
 
468
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
469
                                               -Wunreachable-code */
487
470
  if(ret == NULL)
488
471
    ret = "(unknown)";
489
472
  return ret;
490
473
}
491
474
 
492
475
/* GnuTLS log function callback */
493
 
__attribute__((nonnull))
494
476
static void debuggnutls(__attribute__((unused)) int level,
495
477
                        const char* string){
496
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
497
479
}
498
480
 
499
 
__attribute__((nonnull, warn_unused_result))
500
481
static int init_gnutls_global(const char *pubkeyfilename,
501
 
                              const char *seckeyfilename,
502
 
                              mandos_context *mc){
 
482
                              const char *seckeyfilename){
503
483
  int ret;
504
484
  
505
485
  if(debug){
522
502
  }
523
503
  
524
504
  /* OpenPGP credentials */
525
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
526
506
  if(ret != GNUTLS_E_SUCCESS){
527
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
528
508
                 safer_gnutls_strerror(ret));
538
518
  }
539
519
  
540
520
  ret = gnutls_certificate_set_openpgp_key_file
541
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
521
    (mc.cred, pubkeyfilename, seckeyfilename,
542
522
     GNUTLS_OPENPGP_FMT_BASE64);
543
523
  if(ret != GNUTLS_E_SUCCESS){
544
524
    fprintf_plus(stderr,
550
530
  }
551
531
  
552
532
  /* GnuTLS server initialization */
553
 
  ret = gnutls_dh_params_init(&mc->dh_params);
 
533
  ret = gnutls_dh_params_init(&mc.dh_params);
554
534
  if(ret != GNUTLS_E_SUCCESS){
555
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
556
536
                 " initialization: %s\n",
557
537
                 safer_gnutls_strerror(ret));
558
538
    goto globalfail;
559
539
  }
560
 
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
 
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
561
541
  if(ret != GNUTLS_E_SUCCESS){
562
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
563
543
                 safer_gnutls_strerror(ret));
564
544
    goto globalfail;
565
545
  }
566
546
  
567
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
547
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
568
548
  
569
549
  return 0;
570
550
  
571
551
 globalfail:
572
552
  
573
 
  gnutls_certificate_free_credentials(mc->cred);
 
553
  gnutls_certificate_free_credentials(mc.cred);
574
554
  gnutls_global_deinit();
575
 
  gnutls_dh_params_deinit(mc->dh_params);
 
555
  gnutls_dh_params_deinit(mc.dh_params);
576
556
  return -1;
577
557
}
578
558
 
579
 
__attribute__((nonnull, warn_unused_result))
580
 
static int init_gnutls_session(gnutls_session_t *session,
581
 
                               mandos_context *mc){
 
559
static int init_gnutls_session(gnutls_session_t *session){
582
560
  int ret;
583
561
  /* GnuTLS session creation */
584
562
  do {
596
574
  {
597
575
    const char *err;
598
576
    do {
599
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
577
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
600
578
      if(quit_now){
601
579
        gnutls_deinit(*session);
602
580
        return -1;
613
591
  
614
592
  do {
615
593
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
616
 
                                 mc->cred);
 
594
                                 mc.cred);
617
595
    if(quit_now){
618
596
      gnutls_deinit(*session);
619
597
      return -1;
629
607
  /* ignore client certificate if any. */
630
608
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
631
609
  
632
 
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
 
610
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
633
611
  
634
612
  return 0;
635
613
}
639
617
                      __attribute__((unused)) const char *txt){}
640
618
 
641
619
/* 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,
 
620
static int start_mandos_communication(const char *ip, uint16_t port,
644
621
                                      AvahiIfIndex if_index,
645
 
                                      int af, mandos_context *mc){
 
622
                                      int af){
646
623
  int ret, tcp_sd = -1;
647
624
  ssize_t sret;
648
 
  struct sockaddr_storage to;
 
625
  union {
 
626
    struct sockaddr_in in;
 
627
    struct sockaddr_in6 in6;
 
628
  } to;
649
629
  char *buffer = NULL;
650
630
  char *decrypted_buffer = NULL;
651
631
  size_t buffer_length = 0;
675
655
    return -1;
676
656
  }
677
657
  
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);
 
658
  ret = init_gnutls_session(&session);
711
659
  if(ret != 0){
712
660
    return -1;
713
661
  }
714
662
  
715
663
  if(debug){
716
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
717
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
665
                 PRIu16 "\n", ip, port);
718
666
  }
719
667
  
720
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
732
680
  
733
681
  memset(&to, 0, sizeof(to));
734
682
  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);
 
683
    to.in6.sin6_family = (sa_family_t)af;
 
684
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
737
685
  } 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);
 
686
    to.in.sin_family = (sa_family_t)af;
 
687
    ret = inet_pton(af, ip, &to.in.sin_addr);
740
688
  }
741
689
  if(ret < 0 ){
742
690
    int e = errno;
751
699
    goto mandos_end;
752
700
  }
753
701
  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)){
 
702
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
703
                                       -Wconversion and
 
704
                                       -Wunreachable-code */
 
705
    
 
706
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
708
                                -Wunreachable-code*/
757
709
      if(if_index == AVAHI_IF_UNSPEC){
758
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
759
711
                     " incomplete without a network interface\n");
761
713
        goto mandos_end;
762
714
      }
763
715
      /* Set the network interface number as scope */
764
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
716
      to.in6.sin6_scope_id = (uint32_t)if_index;
765
717
    }
766
718
  } else {
767
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
719
    to.in.sin_port = htons(port); /* Spurious warnings from
 
720
                                     -Wconversion and
 
721
                                     -Wunreachable-code */
768
722
  }
769
723
  
770
724
  if(quit_now){
778
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
779
733
        perror_plus("if_indextoname");
780
734
      } else {
781
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
782
 
                     "\n", ip, interface, (uintmax_t)port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
783
737
      }
784
738
    } else {
785
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
786
 
                   ip, (uintmax_t)port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
787
741
    }
788
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
789
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
 
744
    const char *pcret;
790
745
    if(af == AF_INET6){
791
 
      ret = getnameinfo((struct sockaddr *)&to,
792
 
                        sizeof(struct sockaddr_in6),
793
 
                        addrstr, sizeof(addrstr), NULL, 0,
794
 
                        NI_NUMERICHOST);
 
746
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
747
                        sizeof(addrstr));
795
748
    } else {
796
 
      ret = getnameinfo((struct sockaddr *)&to,
797
 
                        sizeof(struct sockaddr_in),
798
 
                        addrstr, sizeof(addrstr), NULL, 0,
799
 
                        NI_NUMERICHOST);
 
749
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
750
                        sizeof(addrstr));
800
751
    }
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);
 
752
    if(pcret == NULL){
 
753
      perror_plus("inet_ntop");
 
754
    } else {
 
755
      if(strcmp(addrstr, ip) != 0){
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
757
      }
807
758
    }
808
759
  }
809
760
  
813
764
  }
814
765
  
815
766
  if(af == AF_INET6){
816
 
    ret = connect(tcp_sd, (struct sockaddr *)&to,
817
 
                  sizeof(struct sockaddr_in6));
 
767
    ret = connect(tcp_sd, &to.in6, sizeof(to));
818
768
  } else {
819
 
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
820
 
                  sizeof(struct sockaddr_in));
 
769
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
821
770
  }
822
771
  if(ret < 0){
823
 
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
772
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
824
773
      int e = errno;
825
774
      perror_plus("connect");
826
775
      errno = e;
872
821
    goto mandos_end;
873
822
  }
874
823
  
875
 
  /* This casting via intptr_t is to eliminate warning about casting
876
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
877
 
     function "set-session-transport-fd!" does it. */
878
 
  gnutls_transport_set_ptr(session,
879
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
824
  /* Spurious warning from -Wint-to-pointer-cast */
 
825
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
880
826
  
881
827
  if(quit_now){
882
828
    errno = EINTR;
987
933
  if(buffer_length > 0){
988
934
    ssize_t decrypted_buffer_size;
989
935
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
990
 
                                               &decrypted_buffer, mc);
 
936
                                               &decrypted_buffer);
991
937
    if(decrypted_buffer_size >= 0){
992
938
      
993
939
      written = 0;
1041
987
  return retval;
1042
988
}
1043
989
 
1044
 
__attribute__((nonnull))
1045
990
static void resolve_callback(AvahiSServiceResolver *r,
1046
991
                             AvahiIfIndex interface,
1047
992
                             AvahiProtocol proto,
1055
1000
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1056
1001
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1057
1002
                             flags,
1058
 
                             void *mc){
1059
 
  if(r == NULL){
1060
 
    return;
1061
 
  }
 
1003
                             AVAHI_GCC_UNUSED void* userdata){
 
1004
  assert(r);
1062
1005
  
1063
1006
  /* Called whenever a service has been resolved successfully or
1064
1007
     timed out */
1073
1016
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1074
1017
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1075
1018
                 domain,
1076
 
                 avahi_strerror(avahi_server_errno
1077
 
                                (((mandos_context*)mc)->server)));
 
1019
                 avahi_strerror(avahi_server_errno(mc.server)));
1078
1020
    break;
1079
1021
    
1080
1022
  case AVAHI_RESOLVER_FOUND:
1086
1028
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1087
1029
                     host_name, ip, (intmax_t)interface, port);
1088
1030
      }
1089
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1090
 
                                           interface,
1091
 
                                           avahi_proto_to_af(proto),
1092
 
                                           mc);
 
1031
      int ret = start_mandos_communication(ip, port, interface,
 
1032
                                           avahi_proto_to_af(proto));
1093
1033
      if(ret == 0){
1094
 
        avahi_simple_poll_quit(simple_poll);
 
1034
        avahi_simple_poll_quit(mc.simple_poll);
1095
1035
      } else {
1096
 
        if(not add_server(ip, (in_port_t)port, interface,
1097
 
                          avahi_proto_to_af(proto),
1098
 
                          &((mandos_context*)mc)->current_server)){
 
1036
        if(not add_server(ip, port, interface,
 
1037
                          avahi_proto_to_af(proto))){
1099
1038
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1100
1039
                       " list\n", name);
1101
1040
        }
1114
1053
                            const char *domain,
1115
1054
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1116
1055
                            flags,
1117
 
                            void *mc){
1118
 
  if(b == NULL){
1119
 
    return;
1120
 
  }
 
1056
                            AVAHI_GCC_UNUSED void* userdata){
 
1057
  assert(b);
1121
1058
  
1122
1059
  /* Called whenever a new services becomes available on the LAN or
1123
1060
     is removed from the LAN */
1131
1068
  case AVAHI_BROWSER_FAILURE:
1132
1069
    
1133
1070
    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);
 
1071
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1072
    avahi_simple_poll_quit(mc.simple_poll);
1137
1073
    return;
1138
1074
    
1139
1075
  case AVAHI_BROWSER_NEW:
1142
1078
       the callback function is called the Avahi server will free the
1143
1079
       resolver for us. */
1144
1080
    
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)
 
1081
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1082
                                    name, type, domain, protocol, 0,
 
1083
                                    resolve_callback, NULL) == NULL)
1149
1084
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1150
1085
                   " %s\n", name,
1151
 
                   avahi_strerror(avahi_server_errno
1152
 
                                  (((mandos_context*)mc)->server)));
 
1086
                   avahi_strerror(avahi_server_errno(mc.server)));
1153
1087
    break;
1154
1088
    
1155
1089
  case AVAHI_BROWSER_REMOVE:
1174
1108
  signal_received = sig;
1175
1109
  int old_errno = errno;
1176
1110
  /* set main loop to exit */
1177
 
  if(simple_poll != NULL){
1178
 
    avahi_simple_poll_quit(simple_poll);
 
1111
  if(mc.simple_poll != NULL){
 
1112
    avahi_simple_poll_quit(mc.simple_poll);
1179
1113
  }
1180
1114
  errno = old_errno;
1181
1115
}
1182
1116
 
1183
 
__attribute__((nonnull, warn_unused_result))
1184
1117
bool get_flags(const char *ifname, struct ifreq *ifr){
1185
1118
  int ret;
1186
 
  error_t ret_errno;
1187
1119
  
1188
1120
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1189
1121
  if(s < 0){
1190
 
    ret_errno = errno;
1191
1122
    perror_plus("socket");
1192
 
    errno = ret_errno;
1193
1123
    return false;
1194
1124
  }
1195
1125
  strcpy(ifr->ifr_name, ifname);
1196
1126
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1197
1127
  if(ret == -1){
1198
1128
    if(debug){
1199
 
      ret_errno = errno;
1200
1129
      perror_plus("ioctl SIOCGIFFLAGS");
1201
 
      errno = ret_errno;
1202
1130
    }
1203
1131
    return false;
1204
1132
  }
1205
1133
  return true;
1206
1134
}
1207
1135
 
1208
 
__attribute__((nonnull, warn_unused_result))
1209
1136
bool good_flags(const char *ifname, const struct ifreq *ifr){
1210
1137
  
1211
1138
  /* Reject the loopback device */
1253
1180
 * corresponds to an acceptable network device.
1254
1181
 * (This function is passed to scandir(3) as a filter function.)
1255
1182
 */
1256
 
__attribute__((nonnull, warn_unused_result))
1257
1183
int good_interface(const struct dirent *if_entry){
1258
1184
  if(if_entry->d_name[0] == '.'){
1259
1185
    return 0;
1275
1201
}
1276
1202
 
1277
1203
/* 
1278
 
 * This function determines if a network interface is up.
1279
 
 */
1280
 
__attribute__((nonnull, warn_unused_result))
1281
 
bool interface_is_up(const char *interface){
1282
 
  struct ifreq ifr;
1283
 
  if(not get_flags(interface, &ifr)){
1284
 
    if(debug){
1285
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1286
 
                   "\"%s\"\n", interface);
1287
 
    }
1288
 
    return false;
1289
 
  }
1290
 
  
1291
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1292
 
}
1293
 
 
1294
 
/* 
1295
 
 * This function determines if a network interface is running
1296
 
 */
1297
 
__attribute__((nonnull, warn_unused_result))
1298
 
bool interface_is_running(const char *interface){
1299
 
  struct ifreq ifr;
1300
 
  if(not get_flags(interface, &ifr)){
1301
 
    if(debug){
1302
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1303
 
                   "\"%s\"\n", interface);
1304
 
    }
1305
 
    return false;
1306
 
  }
1307
 
  
1308
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1309
 
}
1310
 
 
1311
 
__attribute__((nonnull, pure, warn_unused_result))
 
1204
 * This function determines if a directory entry in /sys/class/net
 
1205
 * corresponds to an acceptable network device which is up.
 
1206
 * (This function is passed to scandir(3) as a filter function.)
 
1207
 */
 
1208
int up_interface(const struct dirent *if_entry){
 
1209
  if(if_entry->d_name[0] == '.'){
 
1210
    return 0;
 
1211
  }
 
1212
  
 
1213
  struct ifreq ifr;
 
1214
  if(not get_flags(if_entry->d_name, &ifr)){
 
1215
    if(debug){
 
1216
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1217
                   "\"%s\"\n", if_entry->d_name);
 
1218
    }
 
1219
    return 0;
 
1220
  }
 
1221
  
 
1222
  /* Reject down interfaces */
 
1223
  if(not (ifr.ifr_flags & IFF_UP)){
 
1224
    if(debug){
 
1225
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1226
                   if_entry->d_name);
 
1227
    }
 
1228
    return 0;
 
1229
  }
 
1230
  
 
1231
  /* Reject non-running interfaces */
 
1232
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1233
    if(debug){
 
1234
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1235
                   if_entry->d_name);
 
1236
    }
 
1237
    return 0;
 
1238
  }
 
1239
  
 
1240
  if(not good_flags(if_entry->d_name, &ifr)){
 
1241
    return 0;
 
1242
  }
 
1243
  return 1;
 
1244
}
 
1245
 
1312
1246
int notdotentries(const struct dirent *direntry){
1313
1247
  /* Skip "." and ".." */
1314
1248
  if(direntry->d_name[0] == '.'
1321
1255
}
1322
1256
 
1323
1257
/* Is this directory entry a runnable program? */
1324
 
__attribute__((nonnull, warn_unused_result))
1325
1258
int runnable_hook(const struct dirent *direntry){
1326
1259
  int ret;
1327
1260
  size_t sret;
1335
1268
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1336
1269
                "abcdefghijklmnopqrstuvwxyz"
1337
1270
                "0123456789"
1338
 
                "_.-");
 
1271
                "_-");
1339
1272
  if((direntry->d_name)[sret] != '\0'){
1340
1273
    /* Contains non-allowed characters */
1341
1274
    if(debug){
1359
1292
    }
1360
1293
    return 0;
1361
1294
  }
1362
 
  free(fullname);
1363
1295
  if(not (S_ISREG(st.st_mode))){
1364
1296
    /* Not a regular file */
1365
1297
    if(debug){
1383
1315
  return 1;
1384
1316
}
1385
1317
 
1386
 
__attribute__((nonnull, warn_unused_result))
1387
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1388
 
                            mandos_context *mc){
 
1318
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1389
1319
  int ret;
1390
1320
  struct timespec now;
1391
1321
  struct timespec waited_time;
1392
1322
  intmax_t block_time;
1393
1323
  
1394
1324
  while(true){
1395
 
    if(mc->current_server == NULL){
1396
 
      if(debug){
 
1325
    if(mc.current_server == NULL){
 
1326
      if (debug){
1397
1327
        fprintf_plus(stderr, "Wait until first server is found."
1398
1328
                     " No timeout!\n");
1399
1329
      }
1400
1330
      ret = avahi_simple_poll_iterate(s, -1);
1401
1331
    } else {
1402
 
      if(debug){
 
1332
      if (debug){
1403
1333
        fprintf_plus(stderr, "Check current_server if we should run"
1404
1334
                     " it, or wait\n");
1405
1335
      }
1412
1342
      /* Calculating in ms how long time between now and server
1413
1343
         who we visted longest time ago. Now - last seen.  */
1414
1344
      waited_time.tv_sec = (now.tv_sec
1415
 
                            - mc->current_server->last_seen.tv_sec);
 
1345
                            - mc.current_server->last_seen.tv_sec);
1416
1346
      waited_time.tv_nsec = (now.tv_nsec
1417
 
                             - mc->current_server->last_seen.tv_nsec);
 
1347
                             - mc.current_server->last_seen.tv_nsec);
1418
1348
      /* total time is 10s/10,000ms.
1419
1349
         Converting to s from ms by dividing by 1,000,
1420
1350
         and ns to ms by dividing by 1,000,000. */
1422
1352
                     - ((intmax_t)waited_time.tv_sec * 1000))
1423
1353
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1424
1354
      
1425
 
      if(debug){
 
1355
      if (debug){
1426
1356
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1427
1357
                     block_time);
1428
1358
      }
1429
1359
      
1430
1360
      if(block_time <= 0){
1431
 
        ret = start_mandos_communication(mc->current_server->ip,
1432
 
                                         mc->current_server->port,
1433
 
                                         mc->current_server->if_index,
1434
 
                                         mc->current_server->af, mc);
 
1361
        ret = start_mandos_communication(mc.current_server->ip,
 
1362
                                         mc.current_server->port,
 
1363
                                         mc.current_server->if_index,
 
1364
                                         mc.current_server->af);
1435
1365
        if(ret == 0){
1436
 
          avahi_simple_poll_quit(s);
 
1366
          avahi_simple_poll_quit(mc.simple_poll);
1437
1367
          return 0;
1438
1368
        }
1439
1369
        ret = clock_gettime(CLOCK_MONOTONIC,
1440
 
                            &mc->current_server->last_seen);
 
1370
                            &mc.current_server->last_seen);
1441
1371
        if(ret == -1){
1442
1372
          perror_plus("clock_gettime");
1443
1373
          return -1;
1444
1374
        }
1445
 
        mc->current_server = mc->current_server->next;
 
1375
        mc.current_server = mc.current_server->next;
1446
1376
        block_time = 0;         /* Call avahi to find new Mandos
1447
1377
                                   servers, but don't block */
1448
1378
      }
1450
1380
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1451
1381
    }
1452
1382
    if(ret != 0){
1453
 
      if(ret > 0 or errno != EINTR){
 
1383
      if (ret > 0 or errno != EINTR){
1454
1384
        return (ret != 1) ? ret : 0;
1455
1385
      }
1456
1386
    }
1457
1387
  }
1458
1388
}
1459
1389
 
1460
 
/* Set effective uid to 0, return errno */
1461
 
__attribute__((warn_unused_result))
1462
 
error_t raise_privileges(void){
1463
 
  error_t old_errno = errno;
1464
 
  error_t ret_errno = 0;
1465
 
  if(seteuid(0) == -1){
1466
 
    ret_errno = errno;
1467
 
    perror_plus("seteuid");
1468
 
  }
1469
 
  errno = old_errno;
1470
 
  return ret_errno;
1471
 
}
1472
 
 
1473
 
/* Set effective and real user ID to 0.  Return errno. */
1474
 
__attribute__((warn_unused_result))
1475
 
error_t raise_privileges_permanently(void){
1476
 
  error_t old_errno = errno;
1477
 
  error_t ret_errno = raise_privileges();
1478
 
  if(ret_errno != 0){
1479
 
    errno = old_errno;
1480
 
    return ret_errno;
1481
 
  }
1482
 
  if(setuid(0) == -1){
1483
 
    ret_errno = errno;
1484
 
    perror_plus("seteuid");
1485
 
  }
1486
 
  errno = old_errno;
1487
 
  return ret_errno;
1488
 
}
1489
 
 
1490
 
/* Set effective user ID to unprivileged saved user ID */
1491
 
__attribute__((warn_unused_result))
1492
 
error_t lower_privileges(void){
1493
 
  error_t old_errno = errno;
1494
 
  error_t ret_errno = 0;
1495
 
  if(seteuid(uid) == -1){
1496
 
    ret_errno = errno;
1497
 
    perror_plus("seteuid");
1498
 
  }
1499
 
  errno = old_errno;
1500
 
  return ret_errno;
1501
 
}
1502
 
 
1503
 
/* Lower privileges permanently */
1504
 
__attribute__((warn_unused_result))
1505
 
error_t lower_privileges_permanently(void){
1506
 
  error_t old_errno = errno;
1507
 
  error_t ret_errno = 0;
1508
 
  if(setuid(uid) == -1){
1509
 
    ret_errno = errno;
1510
 
    perror_plus("setuid");
1511
 
  }
1512
 
  errno = old_errno;
1513
 
  return ret_errno;
1514
 
}
1515
 
 
1516
 
__attribute__((nonnull))
1517
 
void run_network_hooks(const char *mode, const char *interface,
 
1390
bool run_network_hooks(const char *mode, const char *interface,
1518
1391
                       const float delay){
1519
1392
  struct dirent **direntries;
 
1393
  struct dirent *direntry;
 
1394
  int ret;
1520
1395
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1521
1396
                         alphasort);
1522
1397
  if(numhooks == -1){
1523
 
    if(errno == ENOENT){
1524
 
      if(debug){
1525
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1526
 
                     " found\n", hookdir);
1527
 
      }
1528
 
    } else {
1529
 
      perror_plus("scandir");
1530
 
    }
 
1398
    perror_plus("scandir");
1531
1399
  } else {
1532
 
    struct dirent *direntry;
1533
 
    int ret;
1534
1400
    int devnull = open("/dev/null", O_RDONLY);
1535
1401
    for(int i = 0; i < numhooks; i++){
1536
1402
      direntry = direntries[i];
1548
1414
      if(hook_pid == 0){
1549
1415
        /* Child */
1550
1416
        /* Raise privileges */
1551
 
        if(raise_privileges_permanently() != 0){
1552
 
          perror_plus("Failed to raise privileges");
1553
 
          _exit(EX_NOPERM);
 
1417
        errno = 0;
 
1418
        ret = seteuid(0);
 
1419
        if(ret == -1){
 
1420
          perror_plus("seteuid");
 
1421
        }
 
1422
        /* Raise privileges even more */
 
1423
        errno = 0;
 
1424
        ret = setuid(0);
 
1425
        if(ret == -1){
 
1426
          perror_plus("setuid");
1554
1427
        }
1555
1428
        /* Set group */
1556
1429
        errno = 0;
1557
1430
        ret = setgid(0);
1558
1431
        if(ret == -1){
1559
1432
          perror_plus("setgid");
1560
 
          _exit(EX_NOPERM);
1561
1433
        }
1562
1434
        /* Reset supplementary groups */
1563
1435
        errno = 0;
1564
1436
        ret = setgroups(0, NULL);
1565
1437
        if(ret == -1){
1566
1438
          perror_plus("setgroups");
1567
 
          _exit(EX_NOPERM);
1568
 
        }
1569
 
        ret = dup2(devnull, STDIN_FILENO);
1570
 
        if(ret == -1){
1571
 
          perror_plus("dup2(devnull, STDIN_FILENO)");
1572
 
          _exit(EX_OSERR);
1573
 
        }
1574
 
        ret = close(devnull);
1575
 
        if(ret == -1){
1576
 
          perror_plus("close");
1577
 
          _exit(EX_OSERR);
1578
 
        }
1579
 
        ret = dup2(STDERR_FILENO, STDOUT_FILENO);
1580
 
        if(ret == -1){
1581
 
          perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
1582
 
          _exit(EX_OSERR);
1583
 
        }
 
1439
        }
 
1440
        dup2(devnull, STDIN_FILENO);
 
1441
        close(devnull);
 
1442
        dup2(STDERR_FILENO, STDOUT_FILENO);
1584
1443
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1585
1444
        if(ret == -1){
1586
1445
          perror_plus("setenv");
1602
1461
          _exit(EX_OSERR);
1603
1462
        }
1604
1463
        char *delaystring;
1605
 
        ret = asprintf(&delaystring, "%f", (double)delay);
 
1464
        ret = asprintf(&delaystring, "%f", delay);
1606
1465
        if(ret == -1){
1607
1466
          perror_plus("asprintf");
1608
1467
          _exit(EX_OSERR);
1661
1520
    }
1662
1521
    close(devnull);
1663
1522
  }
1664
 
}
1665
 
 
1666
 
__attribute__((nonnull, warn_unused_result))
1667
 
error_t bring_up_interface(const char *const interface,
1668
 
                           const float delay){
1669
 
  error_t old_errno = errno;
1670
 
  int ret;
1671
 
  struct ifreq network;
1672
 
  unsigned int if_index = if_nametoindex(interface);
1673
 
  if(if_index == 0){
1674
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1675
 
    errno = old_errno;
1676
 
    return ENXIO;
1677
 
  }
1678
 
  
1679
 
  if(quit_now){
1680
 
    errno = old_errno;
1681
 
    return EINTR;
1682
 
  }
1683
 
  
1684
 
  if(not interface_is_up(interface)){
1685
 
    error_t ret_errno = 0, ioctl_errno = 0;
1686
 
    if(not get_flags(interface, &network)){
1687
 
      ret_errno = errno;
1688
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1689
 
                   "\"%s\"\n", interface);
1690
 
      errno = old_errno;
1691
 
      return ret_errno;
1692
 
    }
1693
 
    network.ifr_flags |= IFF_UP; /* set flag */
1694
 
    
1695
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1696
 
    if(sd == -1){
1697
 
      ret_errno = errno;
1698
 
      perror_plus("socket");
1699
 
      errno = old_errno;
1700
 
      return ret_errno;
1701
 
    }
1702
 
    
1703
 
    if(quit_now){
1704
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1705
 
      if(ret == -1){
1706
 
        perror_plus("close");
1707
 
      }
1708
 
      errno = old_errno;
1709
 
      return EINTR;
1710
 
    }
1711
 
    
1712
 
    if(debug){
1713
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1714
 
                   interface);
1715
 
    }
1716
 
    
1717
 
    /* Raise privileges */
1718
 
    ret_errno = raise_privileges();
1719
 
    if(ret_errno != 0){
1720
 
      perror_plus("Failed to raise privileges");
1721
 
    }
1722
 
    
1723
 
#ifdef __linux__
1724
 
    int ret_linux;
1725
 
    bool restore_loglevel = false;
1726
 
    if(ret_errno == 0){
1727
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1728
 
         messages about the network interface to mess up the prompt */
1729
 
      ret_linux = klogctl(8, NULL, 5);
1730
 
      if(ret_linux == -1){
1731
 
        perror_plus("klogctl");
1732
 
      } else {
1733
 
        restore_loglevel = true;
1734
 
      }
1735
 
    }
1736
 
#endif  /* __linux__ */
1737
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1738
 
    ioctl_errno = errno;
1739
 
#ifdef __linux__
1740
 
    if(restore_loglevel){
1741
 
      ret_linux = klogctl(7, NULL, 0);
1742
 
      if(ret_linux == -1){
1743
 
        perror_plus("klogctl");
1744
 
      }
1745
 
    }
1746
 
#endif  /* __linux__ */
1747
 
    
1748
 
    /* If raise_privileges() succeeded above */
1749
 
    if(ret_errno == 0){
1750
 
      /* Lower privileges */
1751
 
      ret_errno = lower_privileges();
1752
 
      if(ret_errno != 0){
1753
 
        errno = ret_errno;
1754
 
        perror_plus("Failed to lower privileges");
1755
 
      }
1756
 
    }
1757
 
    
1758
 
    /* Close the socket */
1759
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1760
 
    if(ret == -1){
1761
 
      perror_plus("close");
1762
 
    }
1763
 
    
1764
 
    if(ret_setflags == -1){
1765
 
      errno = ioctl_errno;
1766
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1767
 
      errno = old_errno;
1768
 
      return ioctl_errno;
1769
 
    }
1770
 
  } else if(debug){
1771
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1772
 
                 interface);
1773
 
  }
1774
 
  
1775
 
  /* Sleep checking until interface is running.
1776
 
     Check every 0.25s, up to total time of delay */
1777
 
  for(int i=0; i < delay * 4; i++){
1778
 
    if(interface_is_running(interface)){
1779
 
      break;
1780
 
    }
1781
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1782
 
    ret = nanosleep(&sleeptime, NULL);
1783
 
    if(ret == -1 and errno != EINTR){
1784
 
      perror_plus("nanosleep");
1785
 
    }
1786
 
  }
1787
 
  
1788
 
  errno = old_errno;
1789
 
  return 0;
1790
 
}
1791
 
 
1792
 
__attribute__((nonnull, warn_unused_result))
1793
 
error_t take_down_interface(const char *const interface){
1794
 
  error_t old_errno = errno;
1795
 
  struct ifreq network;
1796
 
  unsigned int if_index = if_nametoindex(interface);
1797
 
  if(if_index == 0){
1798
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1799
 
    errno = old_errno;
1800
 
    return ENXIO;
1801
 
  }
1802
 
  if(interface_is_up(interface)){
1803
 
    error_t ret_errno = 0, ioctl_errno = 0;
1804
 
    if(not get_flags(interface, &network) and debug){
1805
 
      ret_errno = errno;
1806
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1807
 
                   "\"%s\"\n", interface);
1808
 
      errno = old_errno;
1809
 
      return ret_errno;
1810
 
    }
1811
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1812
 
    
1813
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1814
 
    if(sd == -1){
1815
 
      ret_errno = errno;
1816
 
      perror_plus("socket");
1817
 
      errno = old_errno;
1818
 
      return ret_errno;
1819
 
    }
1820
 
    
1821
 
    if(debug){
1822
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1823
 
                   interface);
1824
 
    }
1825
 
    
1826
 
    /* Raise privileges */
1827
 
    ret_errno = raise_privileges();
1828
 
    if(ret_errno != 0){
1829
 
      perror_plus("Failed to raise privileges");
1830
 
    }
1831
 
    
1832
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1833
 
    ioctl_errno = errno;
1834
 
    
1835
 
    /* If raise_privileges() succeeded above */
1836
 
    if(ret_errno == 0){
1837
 
      /* Lower privileges */
1838
 
      ret_errno = lower_privileges();
1839
 
      if(ret_errno != 0){
1840
 
        errno = ret_errno;
1841
 
        perror_plus("Failed to lower privileges");
1842
 
      }
1843
 
    }
1844
 
    
1845
 
    /* Close the socket */
1846
 
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
1847
 
    if(ret == -1){
1848
 
      perror_plus("close");
1849
 
    }
1850
 
    
1851
 
    if(ret_setflags == -1){
1852
 
      errno = ioctl_errno;
1853
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1854
 
      errno = old_errno;
1855
 
      return ioctl_errno;
1856
 
    }
1857
 
  } else if(debug){
1858
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1859
 
                 interface);
1860
 
  }
1861
 
  
1862
 
  errno = old_errno;
1863
 
  return 0;
 
1523
  return true;
1864
1524
}
1865
1525
 
1866
1526
int main(int argc, char *argv[]){
1867
 
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
1868
 
                        .priority = "SECURE256:!CTYPE-X.509:"
1869
 
                        "+CTYPE-OPENPGP", .current_server = NULL,
1870
 
                        .interfaces = NULL, .interfaces_size = 0 };
1871
1527
  AvahiSServiceBrowser *sb = NULL;
1872
 
  error_t ret_errno;
 
1528
  int error;
1873
1529
  int ret;
1874
1530
  intmax_t tmpmax;
1875
1531
  char *tmp;
1876
1532
  int exitcode = EXIT_SUCCESS;
1877
 
  char *interfaces_to_take_down = NULL;
1878
 
  size_t interfaces_to_take_down_size = 0;
1879
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
1880
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
1881
 
  char *tempdir = NULL;
 
1533
  const char *interface = "";
 
1534
  struct ifreq network;
 
1535
  int sd = -1;
 
1536
  bool take_down_interface = false;
 
1537
  uid_t uid;
 
1538
  gid_t gid;
 
1539
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1540
  bool tempdir_created = false;
1882
1541
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1883
1542
  const char *seckey = PATHDIR "/" SECKEY;
1884
1543
  const char *pubkey = PATHDIR "/" PUBKEY;
1885
 
  char *interfaces_hooks = NULL;
1886
1544
  
1887
1545
  bool gnutls_initialized = false;
1888
1546
  bool gpgme_initialized = false;
1979
1637
        connect_to = arg;
1980
1638
        break;
1981
1639
      case 'i':                 /* --interface */
1982
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
1983
 
                                 arg, (int)',');
1984
 
        if(ret_errno != 0){
1985
 
          argp_error(state, "%s", strerror(ret_errno));
1986
 
        }
 
1640
        interface = arg;
1987
1641
        break;
1988
1642
      case 's':                 /* --seckey */
1989
1643
        seckey = arg;
2066
1720
    /* Work around Debian bug #633582:
2067
1721
       <http://bugs.debian.org/633582> */
2068
1722
    
2069
 
    /* Re-raise privileges */
2070
 
    ret_errno = raise_privileges();
2071
 
    if(ret_errno != 0){
2072
 
      errno = ret_errno;
2073
 
      perror_plus("Failed to raise privileges");
 
1723
    /* Re-raise priviliges */
 
1724
    errno = 0;
 
1725
    ret = seteuid(0);
 
1726
    if(ret == -1){
 
1727
      perror_plus("seteuid");
2074
1728
    } else {
2075
1729
      struct stat st;
2076
1730
      
2117
1771
      }
2118
1772
    
2119
1773
      /* Lower privileges */
2120
 
      ret_errno = lower_privileges();
2121
 
      if(ret_errno != 0){
2122
 
        errno = ret_errno;
2123
 
        perror_plus("Failed to lower privileges");
2124
 
      }
2125
 
    }
2126
 
  }
2127
 
  
2128
 
  /* Remove invalid interface names (except "none") */
2129
 
  {
2130
 
    char *interface = NULL;
2131
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2132
 
                                 interface))){
2133
 
      if(strcmp(interface, "none") != 0
2134
 
         and if_nametoindex(interface) == 0){
2135
 
        if(interface[0] != '\0'){
2136
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2137
 
                       " \"%s\"\n", interface);
2138
 
        }
2139
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2140
 
        interface = NULL;
 
1774
      errno = 0;
 
1775
      ret = seteuid(uid);
 
1776
      if(ret == -1){
 
1777
        perror_plus("seteuid");
2141
1778
      }
2142
1779
    }
2143
1780
  }
2144
1781
  
2145
1782
  /* Run network hooks */
2146
 
  {
2147
 
    if(mc.interfaces != NULL){
2148
 
      interfaces_hooks = malloc(mc.interfaces_size);
2149
 
      if(interfaces_hooks == NULL){
2150
 
        perror_plus("malloc");
2151
 
        goto end;
2152
 
      }
2153
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2154
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2155
 
    }
2156
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2157
 
                      interfaces_hooks : "", delay);
 
1783
  if(not run_network_hooks("start", interface, delay)){
 
1784
    goto end;
2158
1785
  }
2159
1786
  
2160
1787
  if(not debug){
2161
1788
    avahi_set_log_function(empty_log);
2162
1789
  }
2163
1790
  
 
1791
  if(interface[0] == '\0'){
 
1792
    struct dirent **direntries;
 
1793
    /* First look for interfaces that are up */
 
1794
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1795
                  alphasort);
 
1796
    if(ret == 0){
 
1797
      /* No up interfaces, look for any good interfaces */
 
1798
      free(direntries);
 
1799
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1800
                    alphasort);
 
1801
    }
 
1802
    if(ret >= 1){
 
1803
      /* Pick the first interface returned */
 
1804
      interface = strdup(direntries[0]->d_name);
 
1805
      if(debug){
 
1806
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1807
      }
 
1808
      if(interface == NULL){
 
1809
        perror_plus("malloc");
 
1810
        free(direntries);
 
1811
        exitcode = EXIT_FAILURE;
 
1812
        goto end;
 
1813
      }
 
1814
      free(direntries);
 
1815
    } else {
 
1816
      free(direntries);
 
1817
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1818
      exitcode = EXIT_FAILURE;
 
1819
      goto end;
 
1820
    }
 
1821
  }
 
1822
  
2164
1823
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2165
1824
     from the signal handler */
2166
1825
  /* Initialize the pseudo-RNG for Avahi */
2167
1826
  srand((unsigned int) time(NULL));
2168
 
  simple_poll = avahi_simple_poll_new();
2169
 
  if(simple_poll == NULL){
 
1827
  mc.simple_poll = avahi_simple_poll_new();
 
1828
  if(mc.simple_poll == NULL){
2170
1829
    fprintf_plus(stderr,
2171
1830
                 "Avahi: Failed to create simple poll object.\n");
2172
1831
    exitcode = EX_UNAVAILABLE;
2236
1895
    }
2237
1896
  }
2238
1897
  
2239
 
  /* If no interfaces were specified, make a list */
2240
 
  if(mc.interfaces == NULL){
2241
 
    struct dirent **direntries;
2242
 
    /* Look for any good interfaces */
2243
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2244
 
                  alphasort);
2245
 
    if(ret >= 1){
2246
 
      /* Add all found interfaces to interfaces list */
2247
 
      for(int i = 0; i < ret; ++i){
2248
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2249
 
                             direntries[i]->d_name);
2250
 
        if(ret_errno != 0){
2251
 
          errno = ret_errno;
2252
 
          perror_plus("argz_add");
2253
 
          continue;
2254
 
        }
2255
 
        if(debug){
2256
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2257
 
                       direntries[i]->d_name);
2258
 
        }
2259
 
      }
2260
 
      free(direntries);
2261
 
    } else {
2262
 
      free(direntries);
2263
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2264
 
      exitcode = EXIT_FAILURE;
2265
 
      goto end;
2266
 
    }
2267
 
  }
2268
 
  
2269
 
  /* Bring up interfaces which are down, and remove any "none"s */
2270
 
  {
2271
 
    char *interface = NULL;
2272
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2273
 
                                 interface))){
2274
 
      /* If interface name is "none", stop bringing up interfaces.
2275
 
         Also remove all instances of "none" from the list */
2276
 
      if(strcmp(interface, "none") == 0){
2277
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2278
 
                    interface);
2279
 
        interface = NULL;
2280
 
        while((interface = argz_next(mc.interfaces,
2281
 
                                     mc.interfaces_size, interface))){
2282
 
          if(strcmp(interface, "none") == 0){
2283
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2284
 
                        interface);
2285
 
            interface = NULL;
 
1898
  /* If the interface is down, bring it up */
 
1899
  if(strcmp(interface, "none") != 0){
 
1900
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1901
    if(if_index == 0){
 
1902
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1903
      exitcode = EX_UNAVAILABLE;
 
1904
      goto end;
 
1905
    }
 
1906
    
 
1907
    if(quit_now){
 
1908
      goto end;
 
1909
    }
 
1910
    
 
1911
    /* Re-raise priviliges */
 
1912
    errno = 0;
 
1913
    ret = seteuid(0);
 
1914
    if(ret == -1){
 
1915
      perror_plus("seteuid");
 
1916
    }
 
1917
    
 
1918
#ifdef __linux__
 
1919
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1920
       messages about the network interface to mess up the prompt */
 
1921
    ret = klogctl(8, NULL, 5);
 
1922
    bool restore_loglevel = true;
 
1923
    if(ret == -1){
 
1924
      restore_loglevel = false;
 
1925
      perror_plus("klogctl");
 
1926
    }
 
1927
#endif  /* __linux__ */
 
1928
    
 
1929
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1930
    if(sd < 0){
 
1931
      perror_plus("socket");
 
1932
      exitcode = EX_OSERR;
 
1933
#ifdef __linux__
 
1934
      if(restore_loglevel){
 
1935
        ret = klogctl(7, NULL, 0);
 
1936
        if(ret == -1){
 
1937
          perror_plus("klogctl");
 
1938
        }
 
1939
      }
 
1940
#endif  /* __linux__ */
 
1941
      /* Lower privileges */
 
1942
      errno = 0;
 
1943
      ret = seteuid(uid);
 
1944
      if(ret == -1){
 
1945
        perror_plus("seteuid");
 
1946
      }
 
1947
      goto end;
 
1948
    }
 
1949
    strcpy(network.ifr_name, interface);
 
1950
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1951
    if(ret == -1){
 
1952
      perror_plus("ioctl SIOCGIFFLAGS");
 
1953
#ifdef __linux__
 
1954
      if(restore_loglevel){
 
1955
        ret = klogctl(7, NULL, 0);
 
1956
        if(ret == -1){
 
1957
          perror_plus("klogctl");
 
1958
        }
 
1959
      }
 
1960
#endif  /* __linux__ */
 
1961
      exitcode = EX_OSERR;
 
1962
      /* Lower privileges */
 
1963
      errno = 0;
 
1964
      ret = seteuid(uid);
 
1965
      if(ret == -1){
 
1966
        perror_plus("seteuid");
 
1967
      }
 
1968
      goto end;
 
1969
    }
 
1970
    if((network.ifr_flags & IFF_UP) == 0){
 
1971
      network.ifr_flags |= IFF_UP;
 
1972
      take_down_interface = true;
 
1973
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1974
      if(ret == -1){
 
1975
        take_down_interface = false;
 
1976
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1977
        exitcode = EX_OSERR;
 
1978
#ifdef __linux__
 
1979
        if(restore_loglevel){
 
1980
          ret = klogctl(7, NULL, 0);
 
1981
          if(ret == -1){
 
1982
            perror_plus("klogctl");
2286
1983
          }
2287
1984
        }
 
1985
#endif  /* __linux__ */
 
1986
        /* Lower privileges */
 
1987
        errno = 0;
 
1988
        ret = seteuid(uid);
 
1989
        if(ret == -1){
 
1990
          perror_plus("seteuid");
 
1991
        }
 
1992
        goto end;
 
1993
      }
 
1994
    }
 
1995
    /* Sleep checking until interface is running.
 
1996
       Check every 0.25s, up to total time of delay */
 
1997
    for(int i=0; i < delay * 4; i++){
 
1998
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1999
      if(ret == -1){
 
2000
        perror_plus("ioctl SIOCGIFFLAGS");
 
2001
      } else if(network.ifr_flags & IFF_RUNNING){
2288
2002
        break;
2289
2003
      }
2290
 
      bool interface_was_up = interface_is_up(interface);
2291
 
      errno = bring_up_interface(interface, delay);
2292
 
      if(not interface_was_up){
2293
 
        if(errno != 0){
2294
 
          perror_plus("Failed to bring up interface");
2295
 
        } else {
2296
 
          errno = argz_add(&interfaces_to_take_down,
2297
 
                           &interfaces_to_take_down_size,
2298
 
                           interface);
2299
 
          if(errno != 0){
2300
 
            perror_plus("argz_add");
2301
 
          }
2302
 
        }
2303
 
      }
2304
 
    }
2305
 
    if(debug and (interfaces_to_take_down == NULL)){
2306
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2307
 
    }
2308
 
  }
2309
 
  
2310
 
  /* If we only got one interface, explicitly use only that one */
2311
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2312
 
    if(debug){
2313
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2314
 
                   mc.interfaces);
2315
 
    }
2316
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
 
2004
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
2005
      ret = nanosleep(&sleeptime, NULL);
 
2006
      if(ret == -1 and errno != EINTR){
 
2007
        perror_plus("nanosleep");
 
2008
      }
 
2009
    }
 
2010
    if(not take_down_interface){
 
2011
      /* We won't need the socket anymore */
 
2012
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2013
      if(ret == -1){
 
2014
        perror_plus("close");
 
2015
      }
 
2016
    }
 
2017
#ifdef __linux__
 
2018
    if(restore_loglevel){
 
2019
      /* Restores kernel loglevel to default */
 
2020
      ret = klogctl(7, NULL, 0);
 
2021
      if(ret == -1){
 
2022
        perror_plus("klogctl");
 
2023
      }
 
2024
    }
 
2025
#endif  /* __linux__ */
 
2026
    /* Lower privileges */
 
2027
    errno = 0;
 
2028
    /* Lower privileges */
 
2029
    ret = seteuid(uid);
 
2030
    if(ret == -1){
 
2031
      perror_plus("seteuid");
 
2032
    }
2317
2033
  }
2318
2034
  
2319
2035
  if(quit_now){
2320
2036
    goto end;
2321
2037
  }
2322
2038
  
2323
 
  ret = init_gnutls_global(pubkey, seckey, &mc);
 
2039
  ret = init_gnutls_global(pubkey, seckey);
2324
2040
  if(ret == -1){
2325
2041
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2326
2042
    exitcode = EX_UNAVAILABLE;
2333
2049
    goto end;
2334
2050
  }
2335
2051
  
2336
 
  /* Try /run/tmp before /tmp */
2337
 
  tempdir = mkdtemp(run_tempdir);
2338
 
  if(tempdir == NULL and errno == ENOENT){
2339
 
      if(debug){
2340
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2341
 
                     run_tempdir, old_tempdir);
2342
 
      }
2343
 
      tempdir = mkdtemp(old_tempdir);
2344
 
  }
2345
 
  if(tempdir == NULL){
 
2052
  if(mkdtemp(tempdir) == NULL){
2346
2053
    perror_plus("mkdtemp");
2347
2054
    goto end;
2348
2055
  }
 
2056
  tempdir_created = true;
2349
2057
  
2350
2058
  if(quit_now){
2351
2059
    goto end;
2352
2060
  }
2353
2061
  
2354
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2062
  if(not init_gpgme(pubkey, seckey, tempdir)){
2355
2063
    fprintf_plus(stderr, "init_gpgme failed\n");
2356
2064
    exitcode = EX_UNAVAILABLE;
2357
2065
    goto end;
2367
2075
    /* Connect directly, do not use Zeroconf */
2368
2076
    /* (Mainly meant for debugging) */
2369
2077
    char *address = strrchr(connect_to, ':');
2370
 
    
2371
2078
    if(address == NULL){
2372
2079
      fprintf_plus(stderr, "No colon in address\n");
2373
2080
      exitcode = EX_USAGE;
2378
2085
      goto end;
2379
2086
    }
2380
2087
    
2381
 
    in_port_t port;
 
2088
    uint16_t port;
2382
2089
    errno = 0;
2383
2090
    tmpmax = strtoimax(address+1, &tmp, 10);
2384
2091
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2385
 
       or tmpmax != (in_port_t)tmpmax){
 
2092
       or tmpmax != (uint16_t)tmpmax){
2386
2093
      fprintf_plus(stderr, "Bad port number\n");
2387
2094
      exitcode = EX_USAGE;
2388
2095
      goto end;
2389
2096
    }
2390
 
    
 
2097
  
2391
2098
    if(quit_now){
2392
2099
      goto end;
2393
2100
    }
2394
2101
    
2395
 
    port = (in_port_t)tmpmax;
 
2102
    port = (uint16_t)tmpmax;
2396
2103
    *address = '\0';
2397
2104
    /* Colon in address indicates IPv6 */
2398
2105
    int af;
2414
2121
    }
2415
2122
    
2416
2123
    while(not quit_now){
2417
 
      ret = start_mandos_communication(address, port, if_index, af,
2418
 
                                       &mc);
 
2124
      ret = start_mandos_communication(address, port, if_index, af);
2419
2125
      if(quit_now or ret == 0){
2420
2126
        break;
2421
2127
      }
2423
2129
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2424
2130
                     (int)retry_interval);
2425
2131
      }
2426
 
      sleep((unsigned int)retry_interval);
 
2132
      sleep((int)retry_interval);
2427
2133
    }
2428
2134
    
2429
 
    if(not quit_now){
 
2135
    if (not quit_now){
2430
2136
      exitcode = EXIT_SUCCESS;
2431
2137
    }
2432
2138
    
2447
2153
    config.publish_domain = 0;
2448
2154
    
2449
2155
    /* Allocate a new server */
2450
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2451
 
                                 &config, NULL, NULL, &ret_errno);
 
2156
    mc.server = avahi_server_new(avahi_simple_poll_get
 
2157
                                 (mc.simple_poll), &config, NULL,
 
2158
                                 NULL, &error);
2452
2159
    
2453
2160
    /* Free the Avahi configuration data */
2454
2161
    avahi_server_config_free(&config);
2457
2164
  /* Check if creating the Avahi server object succeeded */
2458
2165
  if(mc.server == NULL){
2459
2166
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2460
 
                 avahi_strerror(ret_errno));
 
2167
                 avahi_strerror(error));
2461
2168
    exitcode = EX_UNAVAILABLE;
2462
2169
    goto end;
2463
2170
  }
2469
2176
  /* Create the Avahi service browser */
2470
2177
  sb = avahi_s_service_browser_new(mc.server, if_index,
2471
2178
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2472
 
                                   NULL, 0, browse_callback,
2473
 
                                   (void *)&mc);
 
2179
                                   NULL, 0, browse_callback, NULL);
2474
2180
  if(sb == NULL){
2475
2181
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2476
2182
                 avahi_strerror(avahi_server_errno(mc.server)));
2487
2193
  if(debug){
2488
2194
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2489
2195
  }
2490
 
  
2491
 
  ret = avahi_loop_with_timeout(simple_poll,
2492
 
                                (int)(retry_interval * 1000), &mc);
 
2196
 
 
2197
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2198
                                (int)(retry_interval * 1000));
2493
2199
  if(debug){
2494
2200
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2495
2201
                 (ret == 0) ? "successfully" : "with error");
2502
2208
  }
2503
2209
  
2504
2210
  /* Cleanup things */
2505
 
  free(mc.interfaces);
2506
 
  
2507
2211
  if(sb != NULL)
2508
2212
    avahi_s_service_browser_free(sb);
2509
2213
  
2510
2214
  if(mc.server != NULL)
2511
2215
    avahi_server_free(mc.server);
2512
2216
  
2513
 
  if(simple_poll != NULL)
2514
 
    avahi_simple_poll_free(simple_poll);
 
2217
  if(mc.simple_poll != NULL)
 
2218
    avahi_simple_poll_free(mc.simple_poll);
2515
2219
  
2516
2220
  if(gnutls_initialized){
2517
2221
    gnutls_certificate_free_credentials(mc.cred);
2534
2238
    }
2535
2239
  }
2536
2240
  
2537
 
  /* Re-raise privileges */
 
2241
  /* Run network hooks */
 
2242
  run_network_hooks("stop", interface, delay);
 
2243
  
 
2244
  /* Re-raise priviliges */
2538
2245
  {
2539
 
    ret_errno = raise_privileges();
2540
 
    if(ret_errno != 0){
2541
 
      perror_plus("Failed to raise privileges");
2542
 
    } else {
2543
 
      
2544
 
      /* Run network hooks */
2545
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2546
 
                        interfaces_hooks : "", delay);
2547
 
      
2548
 
      /* Take down the network interfaces which were brought up */
2549
 
      {
2550
 
        char *interface = NULL;
2551
 
        while((interface=argz_next(interfaces_to_take_down,
2552
 
                                   interfaces_to_take_down_size,
2553
 
                                   interface))){
2554
 
          ret_errno = take_down_interface(interface);
2555
 
          if(ret_errno != 0){
2556
 
            errno = ret_errno;
2557
 
            perror_plus("Failed to take down interface");
2558
 
          }
2559
 
        }
2560
 
        if(debug and (interfaces_to_take_down == NULL)){
2561
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
2562
 
                       " down\n");
2563
 
        }
2564
 
      }
 
2246
    errno = 0;
 
2247
    ret = seteuid(0);
 
2248
    if(ret == -1){
 
2249
      perror_plus("seteuid");
2565
2250
    }
2566
2251
    
2567
 
    ret_errno = lower_privileges_permanently();
2568
 
    if(ret_errno != 0){
2569
 
      perror_plus("Failed to lower privileges permanently");
 
2252
    /* Take down the network interface */
 
2253
    if(take_down_interface and geteuid() == 0){
 
2254
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2255
      if(ret == -1){
 
2256
        perror_plus("ioctl SIOCGIFFLAGS");
 
2257
      } else if(network.ifr_flags & IFF_UP){
 
2258
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2259
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2260
        if(ret == -1){
 
2261
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2262
        }
 
2263
      }
 
2264
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2265
      if(ret == -1){
 
2266
        perror_plus("close");
 
2267
      }
2570
2268
    }
2571
2269
  }
2572
 
  
2573
 
  free(interfaces_to_take_down);
2574
 
  free(interfaces_hooks);
 
2270
  /* Lower privileges permanently */
 
2271
  errno = 0;
 
2272
  ret = setuid(uid);
 
2273
  if(ret == -1){
 
2274
    perror_plus("setuid");
 
2275
  }
2575
2276
  
2576
2277
  /* Removes the GPGME temp directory and all files inside */
2577
 
  if(tempdir != NULL){
 
2278
  if(tempdir_created){
2578
2279
    struct dirent **direntries = NULL;
2579
2280
    struct dirent *direntry = NULL;
2580
2281
    int numentries = scandir(tempdir, &direntries, notdotentries,
2581
2282
                             alphasort);
2582
 
    if(numentries > 0){
 
2283
    if (numentries > 0){
2583
2284
      for(int i = 0; i < numentries; i++){
2584
2285
        direntry = direntries[i];
2585
2286
        char *fullname = NULL;
2597
2298
        free(fullname);
2598
2299
      }
2599
2300
    }
2600
 
    
 
2301
 
2601
2302
    /* need to clean even if 0 because man page doesn't specify */
2602
2303
    free(direntries);
2603
 
    if(numentries == -1){
 
2304
    if (numentries == -1){
2604
2305
      perror_plus("scandir");
2605
2306
    }
2606
2307
    ret = rmdir(tempdir);