/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: 2014-03-29 02:38:15 UTC
  • Revision ID: teddy@recompile.se-20140329023815-bpgxi9v4ikrlcpst
Update copyright year.

* mandos-keygen: Update copyright year.
* plugin-runner.c: - '' -
* plugins.d/askpass-fifo.c: - '' -
* plugins.d/mandos-client.c: - '' -
* plugins.d/password-prompt.c: - '' -
* plugins.d/plymouth.c: - '' -
* plugins.d/splashy.c: - '' -
* plugins.d/usplash.c: - '' -

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