/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-28 22:32:21 UTC
  • Revision ID: teddy@recompile.se-20140328223221-w579qlvlex5if3dn
Fix location and format of signing key file.

* debian/upstream/signing-key.asc: Added.
* debian/upstream-signing-key.pgp: Removed.

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2013 Teddy Hogeborn
 
13
 * Copyright © 2008-2013 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;
170
176
 
171
177
/* Function to use when printing errors */
172
178
void perror_plus(const char *print_text){
 
179
  int e = errno;
173
180
  fprintf(stderr, "Mandos plugin %s: ",
174
181
          program_invocation_short_name);
 
182
  errno = e;
175
183
  perror(print_text);
176
184
}
177
185
 
178
 
__attribute__((format (gnu_printf, 2, 3)))
 
186
__attribute__((format (gnu_printf, 2, 3), nonnull))
179
187
int fprintf_plus(FILE *stream, const char *format, ...){
180
188
  va_list ap;
181
189
  va_start (ap, format);
182
190
  
183
191
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
184
192
                             program_invocation_short_name));
185
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
193
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
186
194
}
187
195
 
188
196
/*
190
198
 * bytes. "buffer_capacity" is how much is currently allocated,
191
199
 * "buffer_length" is how much is already used.
192
200
 */
 
201
__attribute__((nonnull, warn_unused_result))
193
202
size_t incbuffer(char **buffer, size_t buffer_length,
194
203
                 size_t buffer_capacity){
195
204
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
196
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
197
 
    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;
198
211
      return 0;
199
212
    }
 
213
    *buffer = new_buf;
200
214
    buffer_capacity += BUFFER_SIZE;
201
215
  }
202
216
  return buffer_capacity;
203
217
}
204
218
 
205
219
/* Add server to set of servers to retry periodically */
206
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
207
 
                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){
208
223
  int ret;
209
224
  server *new_server = malloc(sizeof(server));
210
225
  if(new_server == NULL){
219
234
    perror_plus("strdup");
220
235
    return false;
221
236
  }
 
237
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
238
  if(ret == -1){
 
239
    perror_plus("clock_gettime");
 
240
    return false;
 
241
  }
222
242
  /* Special case of first server */
223
 
  if (mc.current_server == NULL){
 
243
  if(*current_server == NULL){
224
244
    new_server->next = new_server;
225
245
    new_server->prev = new_server;
226
 
    mc.current_server = new_server;
227
 
  /* Place the new server last in the list */
 
246
    *current_server = new_server;
228
247
  } else {
229
 
    new_server->next = mc.current_server;
230
 
    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;
231
251
    new_server->prev->next = new_server;
232
 
    mc.current_server->prev = new_server;
233
 
  }
234
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
235
 
  if(ret == -1){
236
 
    perror_plus("clock_gettime");
237
 
    return false;
 
252
    (*current_server)->prev = new_server;
238
253
  }
239
254
  return true;
240
255
}
242
257
/* 
243
258
 * Initialize GPGME.
244
259
 */
245
 
static bool init_gpgme(const char *seckey, const char *pubkey,
246
 
                       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){
247
265
  gpgme_error_t rc;
248
266
  gpgme_engine_info_t engine_info;
249
267
  
250
 
  
251
268
  /*
252
269
   * Helper function to insert pub and seckey to the engine keyring.
253
270
   */
254
 
  bool import_key(const char *filename){
 
271
  bool import_key(const char * const filename){
255
272
    int ret;
256
273
    int fd;
257
274
    gpgme_data_t pgp_data;
269
286
      return false;
270
287
    }
271
288
    
272
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
289
    rc = gpgme_op_import(mc->ctx, pgp_data);
273
290
    if(rc != GPG_ERR_NO_ERROR){
274
291
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
275
292
                   gpgme_strsource(rc), gpgme_strerror(rc));
319
336
  }
320
337
  
321
338
  /* Create new GPGME "context" */
322
 
  rc = gpgme_new(&(mc.ctx));
 
339
  rc = gpgme_new(&(mc->ctx));
323
340
  if(rc != GPG_ERR_NO_ERROR){
324
341
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
325
342
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
338
355
 * Decrypt OpenPGP data.
339
356
 * Returns -1 on error
340
357
 */
 
358
__attribute__((nonnull, warn_unused_result))
341
359
static ssize_t pgp_packet_decrypt(const char *cryptotext,
342
360
                                  size_t crypto_size,
343
 
                                  char **plaintext){
 
361
                                  char **plaintext,
 
362
                                  mandos_context *mc){
344
363
  gpgme_data_t dh_crypto, dh_plain;
345
364
  gpgme_error_t rc;
346
365
  ssize_t ret;
372
391
  
373
392
  /* Decrypt data from the cryptotext data buffer to the plaintext
374
393
     data buffer */
375
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
394
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
376
395
  if(rc != GPG_ERR_NO_ERROR){
377
396
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
378
397
                 gpgme_strsource(rc), gpgme_strerror(rc));
379
398
    plaintext_length = -1;
380
399
    if(debug){
381
400
      gpgme_decrypt_result_t result;
382
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
401
      result = gpgme_op_decrypt_result(mc->ctx);
383
402
      if(result == NULL){
384
403
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
385
404
      } else {
462
481
  return plaintext_length;
463
482
}
464
483
 
465
 
static const char * safer_gnutls_strerror(int value){
466
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
467
 
                                               -Wunreachable-code */
 
484
__attribute__((warn_unused_result))
 
485
static const char *safer_gnutls_strerror(int value){
 
486
  const char *ret = gnutls_strerror(value);
468
487
  if(ret == NULL)
469
488
    ret = "(unknown)";
470
489
  return ret;
471
490
}
472
491
 
473
492
/* GnuTLS log function callback */
 
493
__attribute__((nonnull))
474
494
static void debuggnutls(__attribute__((unused)) int level,
475
495
                        const char* string){
476
496
  fprintf_plus(stderr, "GnuTLS: %s", string);
477
497
}
478
498
 
 
499
__attribute__((nonnull, warn_unused_result))
479
500
static int init_gnutls_global(const char *pubkeyfilename,
480
 
                              const char *seckeyfilename){
 
501
                              const char *seckeyfilename,
 
502
                              mandos_context *mc){
481
503
  int ret;
482
504
  
483
505
  if(debug){
500
522
  }
501
523
  
502
524
  /* OpenPGP credentials */
503
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
525
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
504
526
  if(ret != GNUTLS_E_SUCCESS){
505
527
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
506
528
                 safer_gnutls_strerror(ret));
516
538
  }
517
539
  
518
540
  ret = gnutls_certificate_set_openpgp_key_file
519
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
541
    (mc->cred, pubkeyfilename, seckeyfilename,
520
542
     GNUTLS_OPENPGP_FMT_BASE64);
521
543
  if(ret != GNUTLS_E_SUCCESS){
522
544
    fprintf_plus(stderr,
528
550
  }
529
551
  
530
552
  /* GnuTLS server initialization */
531
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
553
  ret = gnutls_dh_params_init(&mc->dh_params);
532
554
  if(ret != GNUTLS_E_SUCCESS){
533
555
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
534
556
                 " initialization: %s\n",
535
557
                 safer_gnutls_strerror(ret));
536
558
    goto globalfail;
537
559
  }
538
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
560
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
539
561
  if(ret != GNUTLS_E_SUCCESS){
540
562
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
541
563
                 safer_gnutls_strerror(ret));
542
564
    goto globalfail;
543
565
  }
544
566
  
545
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
567
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
546
568
  
547
569
  return 0;
548
570
  
549
571
 globalfail:
550
572
  
551
 
  gnutls_certificate_free_credentials(mc.cred);
 
573
  gnutls_certificate_free_credentials(mc->cred);
552
574
  gnutls_global_deinit();
553
 
  gnutls_dh_params_deinit(mc.dh_params);
 
575
  gnutls_dh_params_deinit(mc->dh_params);
554
576
  return -1;
555
577
}
556
578
 
557
 
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){
558
582
  int ret;
559
583
  /* GnuTLS session creation */
560
584
  do {
572
596
  {
573
597
    const char *err;
574
598
    do {
575
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
599
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
576
600
      if(quit_now){
577
601
        gnutls_deinit(*session);
578
602
        return -1;
589
613
  
590
614
  do {
591
615
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
592
 
                                 mc.cred);
 
616
                                 mc->cred);
593
617
    if(quit_now){
594
618
      gnutls_deinit(*session);
595
619
      return -1;
605
629
  /* ignore client certificate if any. */
606
630
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
607
631
  
608
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
632
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
609
633
  
610
634
  return 0;
611
635
}
615
639
                      __attribute__((unused)) const char *txt){}
616
640
 
617
641
/* Called when a Mandos server is found */
618
 
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,
619
644
                                      AvahiIfIndex if_index,
620
 
                                      int af){
 
645
                                      int af, mandos_context *mc){
621
646
  int ret, tcp_sd = -1;
622
647
  ssize_t sret;
623
 
  union {
624
 
    struct sockaddr_in in;
625
 
    struct sockaddr_in6 in6;
626
 
  } to;
 
648
  struct sockaddr_storage to;
627
649
  char *buffer = NULL;
628
650
  char *decrypted_buffer = NULL;
629
651
  size_t buffer_length = 0;
653
675
    return -1;
654
676
  }
655
677
  
656
 
  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);
657
711
  if(ret != 0){
658
712
    return -1;
659
713
  }
660
714
  
661
715
  if(debug){
662
716
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
663
 
                 PRIu16 "\n", ip, port);
 
717
                 PRIuMAX "\n", ip, (uintmax_t)port);
664
718
  }
665
719
  
666
720
  tcp_sd = socket(pf, SOCK_STREAM, 0);
678
732
  
679
733
  memset(&to, 0, sizeof(to));
680
734
  if(af == AF_INET6){
681
 
    to.in6.sin6_family = (sa_family_t)af;
682
 
    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);
683
737
  } else {                      /* IPv4 */
684
 
    to.in.sin_family = (sa_family_t)af;
685
 
    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);
686
740
  }
687
741
  if(ret < 0 ){
688
742
    int e = errno;
697
751
    goto mandos_end;
698
752
  }
699
753
  if(af == AF_INET6){
700
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
701
 
                                       -Wconversion and
702
 
                                       -Wunreachable-code */
703
 
    
704
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
705
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
706
 
                                -Wunreachable-code*/
 
754
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
 
755
    if(IN6_IS_ADDR_LINKLOCAL
 
756
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
707
757
      if(if_index == AVAHI_IF_UNSPEC){
708
758
        fprintf_plus(stderr, "An IPv6 link-local address is"
709
759
                     " incomplete without a network interface\n");
711
761
        goto mandos_end;
712
762
      }
713
763
      /* Set the network interface number as scope */
714
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
764
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
715
765
    }
716
766
  } else {
717
 
    to.in.sin_port = htons(port); /* Spurious warnings from
718
 
                                     -Wconversion and
719
 
                                     -Wunreachable-code */
 
767
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
720
768
  }
721
769
  
722
770
  if(quit_now){
730
778
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
731
779
        perror_plus("if_indextoname");
732
780
      } else {
733
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
734
 
                     "\n", ip, interface, port);
 
781
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
782
                     "\n", ip, interface, (uintmax_t)port);
735
783
      }
736
784
    } else {
737
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
738
 
                   ip, port);
 
785
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
786
                   ip, (uintmax_t)port);
739
787
    }
740
788
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
741
789
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
742
 
    const char *pcret;
743
790
    if(af == AF_INET6){
744
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
745
 
                        sizeof(addrstr));
 
791
      ret = getnameinfo((struct sockaddr *)&to,
 
792
                        sizeof(struct sockaddr_in6),
 
793
                        addrstr, sizeof(addrstr), NULL, 0,
 
794
                        NI_NUMERICHOST);
746
795
    } else {
747
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
748
 
                        sizeof(addrstr));
 
796
      ret = getnameinfo((struct sockaddr *)&to,
 
797
                        sizeof(struct sockaddr_in),
 
798
                        addrstr, sizeof(addrstr), NULL, 0,
 
799
                        NI_NUMERICHOST);
749
800
    }
750
 
    if(pcret == NULL){
751
 
      perror_plus("inet_ntop");
752
 
    } else {
753
 
      if(strcmp(addrstr, ip) != 0){
754
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
755
 
      }
 
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);
756
807
    }
757
808
  }
758
809
  
762
813
  }
763
814
  
764
815
  if(af == AF_INET6){
765
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
816
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
817
                  sizeof(struct sockaddr_in6));
766
818
  } else {
767
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
819
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
820
                  sizeof(struct sockaddr_in));
768
821
  }
769
822
  if(ret < 0){
770
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
823
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
771
824
      int e = errno;
772
825
      perror_plus("connect");
773
826
      errno = e;
819
872
    goto mandos_end;
820
873
  }
821
874
  
822
 
  /* Spurious warning from -Wint-to-pointer-cast */
823
 
  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);
824
880
  
825
881
  if(quit_now){
826
882
    errno = EINTR;
931
987
  if(buffer_length > 0){
932
988
    ssize_t decrypted_buffer_size;
933
989
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
934
 
                                               &decrypted_buffer);
 
990
                                               &decrypted_buffer, mc);
935
991
    if(decrypted_buffer_size >= 0){
936
992
      
937
993
      written = 0;
985
1041
  return retval;
986
1042
}
987
1043
 
 
1044
__attribute__((nonnull))
988
1045
static void resolve_callback(AvahiSServiceResolver *r,
989
1046
                             AvahiIfIndex interface,
990
1047
                             AvahiProtocol proto,
998
1055
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
999
1056
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1000
1057
                             flags,
1001
 
                             AVAHI_GCC_UNUSED void* userdata){
1002
 
  assert(r);
 
1058
                             void *mc){
 
1059
  if(r == NULL){
 
1060
    return;
 
1061
  }
1003
1062
  
1004
1063
  /* Called whenever a service has been resolved successfully or
1005
1064
     timed out */
1014
1073
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1015
1074
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1016
1075
                 domain,
1017
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1076
                 avahi_strerror(avahi_server_errno
 
1077
                                (((mandos_context*)mc)->server)));
1018
1078
    break;
1019
1079
    
1020
1080
  case AVAHI_RESOLVER_FOUND:
1026
1086
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1027
1087
                     host_name, ip, (intmax_t)interface, port);
1028
1088
      }
1029
 
      int ret = start_mandos_communication(ip, port, interface,
1030
 
                                           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);
1031
1093
      if(ret == 0){
1032
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1094
        avahi_simple_poll_quit(simple_poll);
1033
1095
      } else {
1034
 
        if(not add_server(ip, port, interface,
1035
 
                          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)){
1036
1099
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1037
1100
                       " list\n", name);
1038
1101
        }
1051
1114
                            const char *domain,
1052
1115
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1053
1116
                            flags,
1054
 
                            AVAHI_GCC_UNUSED void* userdata){
1055
 
  assert(b);
 
1117
                            void *mc){
 
1118
  if(b == NULL){
 
1119
    return;
 
1120
  }
1056
1121
  
1057
1122
  /* Called whenever a new services becomes available on the LAN or
1058
1123
     is removed from the LAN */
1066
1131
  case AVAHI_BROWSER_FAILURE:
1067
1132
    
1068
1133
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1069
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1070
 
    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);
1071
1137
    return;
1072
1138
    
1073
1139
  case AVAHI_BROWSER_NEW:
1076
1142
       the callback function is called the Avahi server will free the
1077
1143
       resolver for us. */
1078
1144
    
1079
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1080
 
                                    name, type, domain, protocol, 0,
1081
 
                                    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)
1082
1149
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1083
1150
                   " %s\n", name,
1084
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1151
                   avahi_strerror(avahi_server_errno
 
1152
                                  (((mandos_context*)mc)->server)));
1085
1153
    break;
1086
1154
    
1087
1155
  case AVAHI_BROWSER_REMOVE:
1106
1174
  signal_received = sig;
1107
1175
  int old_errno = errno;
1108
1176
  /* set main loop to exit */
1109
 
  if(mc.simple_poll != NULL){
1110
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1177
  if(simple_poll != NULL){
 
1178
    avahi_simple_poll_quit(simple_poll);
1111
1179
  }
1112
1180
  errno = old_errno;
1113
1181
}
1114
1182
 
 
1183
__attribute__((nonnull, warn_unused_result))
1115
1184
bool get_flags(const char *ifname, struct ifreq *ifr){
1116
1185
  int ret;
 
1186
  error_t ret_errno;
1117
1187
  
1118
1188
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1119
1189
  if(s < 0){
 
1190
    ret_errno = errno;
1120
1191
    perror_plus("socket");
 
1192
    errno = ret_errno;
1121
1193
    return false;
1122
1194
  }
1123
1195
  strcpy(ifr->ifr_name, ifname);
1124
1196
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1125
1197
  if(ret == -1){
1126
1198
    if(debug){
 
1199
      ret_errno = errno;
1127
1200
      perror_plus("ioctl SIOCGIFFLAGS");
 
1201
      errno = ret_errno;
1128
1202
    }
1129
1203
    return false;
1130
1204
  }
1131
1205
  return true;
1132
1206
}
1133
1207
 
 
1208
__attribute__((nonnull, warn_unused_result))
1134
1209
bool good_flags(const char *ifname, const struct ifreq *ifr){
1135
1210
  
1136
1211
  /* Reject the loopback device */
1178
1253
 * corresponds to an acceptable network device.
1179
1254
 * (This function is passed to scandir(3) as a filter function.)
1180
1255
 */
 
1256
__attribute__((nonnull, warn_unused_result))
1181
1257
int good_interface(const struct dirent *if_entry){
1182
1258
  if(if_entry->d_name[0] == '.'){
1183
1259
    return 0;
1199
1275
}
1200
1276
 
1201
1277
/* 
1202
 
 * This function determines if a directory entry in /sys/class/net
1203
 
 * corresponds to an acceptable network device which is up.
1204
 
 * (This function is passed to scandir(3) as a filter function.)
1205
 
 */
1206
 
int up_interface(const struct dirent *if_entry){
1207
 
  if(if_entry->d_name[0] == '.'){
1208
 
    return 0;
1209
 
  }
1210
 
  
1211
 
  struct ifreq ifr;
1212
 
  if(not get_flags(if_entry->d_name, &ifr)){
1213
 
    if(debug){
1214
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1215
 
                   "\"%s\"\n", if_entry->d_name);
1216
 
    }
1217
 
    return 0;
1218
 
  }
1219
 
  
1220
 
  /* Reject down interfaces */
1221
 
  if(not (ifr.ifr_flags & IFF_UP)){
1222
 
    if(debug){
1223
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1224
 
                   if_entry->d_name);
1225
 
    }
1226
 
    return 0;
1227
 
  }
1228
 
  
1229
 
  /* Reject non-running interfaces */
1230
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1231
 
    if(debug){
1232
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1233
 
                   if_entry->d_name);
1234
 
    }
1235
 
    return 0;
1236
 
  }
1237
 
  
1238
 
  if(not good_flags(if_entry->d_name, &ifr)){
1239
 
    return 0;
1240
 
  }
1241
 
  return 1;
1242
 
}
1243
 
 
 
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))
1244
1312
int notdotentries(const struct dirent *direntry){
1245
1313
  /* Skip "." and ".." */
1246
1314
  if(direntry->d_name[0] == '.'
1253
1321
}
1254
1322
 
1255
1323
/* Is this directory entry a runnable program? */
 
1324
__attribute__((nonnull, warn_unused_result))
1256
1325
int runnable_hook(const struct dirent *direntry){
1257
1326
  int ret;
1258
1327
  size_t sret;
1313
1382
  return 1;
1314
1383
}
1315
1384
 
1316
 
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){
1317
1388
  int ret;
1318
1389
  struct timespec now;
1319
1390
  struct timespec waited_time;
1320
1391
  intmax_t block_time;
1321
1392
  
1322
1393
  while(true){
1323
 
    if(mc.current_server == NULL){
1324
 
      if (debug){
 
1394
    if(mc->current_server == NULL){
 
1395
      if(debug){
1325
1396
        fprintf_plus(stderr, "Wait until first server is found."
1326
1397
                     " No timeout!\n");
1327
1398
      }
1328
1399
      ret = avahi_simple_poll_iterate(s, -1);
1329
1400
    } else {
1330
 
      if (debug){
 
1401
      if(debug){
1331
1402
        fprintf_plus(stderr, "Check current_server if we should run"
1332
1403
                     " it, or wait\n");
1333
1404
      }
1340
1411
      /* Calculating in ms how long time between now and server
1341
1412
         who we visted longest time ago. Now - last seen.  */
1342
1413
      waited_time.tv_sec = (now.tv_sec
1343
 
                            - mc.current_server->last_seen.tv_sec);
 
1414
                            - mc->current_server->last_seen.tv_sec);
1344
1415
      waited_time.tv_nsec = (now.tv_nsec
1345
 
                             - mc.current_server->last_seen.tv_nsec);
 
1416
                             - mc->current_server->last_seen.tv_nsec);
1346
1417
      /* total time is 10s/10,000ms.
1347
1418
         Converting to s from ms by dividing by 1,000,
1348
1419
         and ns to ms by dividing by 1,000,000. */
1350
1421
                     - ((intmax_t)waited_time.tv_sec * 1000))
1351
1422
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1352
1423
      
1353
 
      if (debug){
 
1424
      if(debug){
1354
1425
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1355
1426
                     block_time);
1356
1427
      }
1357
1428
      
1358
1429
      if(block_time <= 0){
1359
 
        ret = start_mandos_communication(mc.current_server->ip,
1360
 
                                         mc.current_server->port,
1361
 
                                         mc.current_server->if_index,
1362
 
                                         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);
1363
1434
        if(ret == 0){
1364
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1435
          avahi_simple_poll_quit(s);
1365
1436
          return 0;
1366
1437
        }
1367
1438
        ret = clock_gettime(CLOCK_MONOTONIC,
1368
 
                            &mc.current_server->last_seen);
 
1439
                            &mc->current_server->last_seen);
1369
1440
        if(ret == -1){
1370
1441
          perror_plus("clock_gettime");
1371
1442
          return -1;
1372
1443
        }
1373
 
        mc.current_server = mc.current_server->next;
 
1444
        mc->current_server = mc->current_server->next;
1374
1445
        block_time = 0;         /* Call avahi to find new Mandos
1375
1446
                                   servers, but don't block */
1376
1447
      }
1378
1449
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1379
1450
    }
1380
1451
    if(ret != 0){
1381
 
      if (ret > 0 or errno != EINTR){
 
1452
      if(ret > 0 or errno != EINTR){
1382
1453
        return (ret != 1) ? ret : 0;
1383
1454
      }
1384
1455
    }
1385
1456
  }
1386
1457
}
1387
1458
 
1388
 
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,
1389
1517
                       const float delay){
1390
1518
  struct dirent **direntries;
1391
 
  struct dirent *direntry;
1392
 
  int ret;
1393
1519
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1394
1520
                         alphasort);
1395
1521
  if(numhooks == -1){
1396
 
    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
    }
1397
1530
  } else {
 
1531
    struct dirent *direntry;
 
1532
    int ret;
1398
1533
    int devnull = open("/dev/null", O_RDONLY);
1399
1534
    for(int i = 0; i < numhooks; i++){
1400
1535
      direntry = direntries[i];
1412
1547
      if(hook_pid == 0){
1413
1548
        /* Child */
1414
1549
        /* Raise privileges */
1415
 
        errno = 0;
1416
 
        ret = seteuid(0);
1417
 
        if(ret == -1){
1418
 
          perror_plus("seteuid");
1419
 
        }
1420
 
        /* Raise privileges even more */
1421
 
        errno = 0;
1422
 
        ret = setuid(0);
1423
 
        if(ret == -1){
1424
 
          perror_plus("setuid");
 
1550
        if(raise_privileges_permanently() != 0){
 
1551
          perror_plus("Failed to raise privileges");
 
1552
          _exit(EX_NOPERM);
1425
1553
        }
1426
1554
        /* Set group */
1427
1555
        errno = 0;
1428
1556
        ret = setgid(0);
1429
1557
        if(ret == -1){
1430
1558
          perror_plus("setgid");
 
1559
          _exit(EX_NOPERM);
1431
1560
        }
1432
1561
        /* Reset supplementary groups */
1433
1562
        errno = 0;
1434
1563
        ret = setgroups(0, NULL);
1435
1564
        if(ret == -1){
1436
1565
          perror_plus("setgroups");
1437
 
        }
1438
 
        dup2(devnull, STDIN_FILENO);
1439
 
        close(devnull);
1440
 
        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
        }
1441
1583
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1442
1584
        if(ret == -1){
1443
1585
          perror_plus("setenv");
1448
1590
          perror_plus("setenv");
1449
1591
          _exit(EX_OSERR);
1450
1592
        }
1451
 
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1593
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1452
1594
        if(ret == -1){
1453
1595
          perror_plus("setenv");
1454
1596
          _exit(EX_OSERR);
1459
1601
          _exit(EX_OSERR);
1460
1602
        }
1461
1603
        char *delaystring;
1462
 
        ret = asprintf(&delaystring, "%f", delay);
 
1604
        ret = asprintf(&delaystring, "%f", (double)delay);
1463
1605
        if(ret == -1){
1464
1606
          perror_plus("asprintf");
1465
1607
          _exit(EX_OSERR);
1471
1613
          _exit(EX_OSERR);
1472
1614
        }
1473
1615
        free(delaystring);
 
1616
        if(connect_to != NULL){
 
1617
          ret = setenv("CONNECT", connect_to, 1);
 
1618
          if(ret == -1){
 
1619
            perror_plus("setenv");
 
1620
            _exit(EX_OSERR);
 
1621
          }
 
1622
        }
1474
1623
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1475
1624
          perror_plus("execl");
1476
1625
          _exit(EXIT_FAILURE);
1511
1660
    }
1512
1661
    close(devnull);
1513
1662
  }
1514
 
  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;
1515
1861
}
1516
1862
 
1517
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 };
1518
1868
  AvahiSServiceBrowser *sb = NULL;
1519
 
  int error;
 
1869
  error_t ret_errno;
1520
1870
  int ret;
1521
1871
  intmax_t tmpmax;
1522
1872
  char *tmp;
1523
1873
  int exitcode = EXIT_SUCCESS;
1524
 
  const char *interface = "";
1525
 
  struct ifreq network;
1526
 
  int sd = -1;
1527
 
  bool take_down_interface = false;
1528
 
  uid_t uid;
1529
 
  gid_t gid;
1530
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1531
 
  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;
1532
1879
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1533
1880
  const char *seckey = PATHDIR "/" SECKEY;
1534
1881
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1882
  char *interfaces_hooks = NULL;
1535
1883
  
1536
1884
  bool gnutls_initialized = false;
1537
1885
  bool gpgme_initialized = false;
1599
1947
        .group = 2 },
1600
1948
      { .name = "retry", .key = 132,
1601
1949
        .arg = "SECONDS",
1602
 
        .doc = "Retry interval used when denied by the mandos server",
 
1950
        .doc = "Retry interval used when denied by the Mandos server",
1603
1951
        .group = 2 },
1604
1952
      { .name = "network-hook-dir", .key = 133,
1605
1953
        .arg = "DIR",
1628
1976
        connect_to = arg;
1629
1977
        break;
1630
1978
      case 'i':                 /* --interface */
1631
 
        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
        }
1632
1984
        break;
1633
1985
      case 's':                 /* --seckey */
1634
1986
        seckey = arg;
1711
2063
    /* Work around Debian bug #633582:
1712
2064
       <http://bugs.debian.org/633582> */
1713
2065
    
1714
 
    /* Re-raise priviliges */
1715
 
    errno = 0;
1716
 
    ret = seteuid(0);
1717
 
    if(ret == -1){
1718
 
      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");
1719
2071
    } else {
1720
2072
      struct stat st;
1721
2073
      
1762
2114
      }
1763
2115
    
1764
2116
      /* Lower privileges */
1765
 
      errno = 0;
1766
 
      ret = seteuid(uid);
1767
 
      if(ret == -1){
1768
 
        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;
1769
2138
      }
1770
2139
    }
1771
2140
  }
1772
2141
  
1773
2142
  /* Run network hooks */
1774
 
  if(not run_network_hooks("start", interface, delay)){
1775
 
    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);
1776
2155
  }
1777
2156
  
1778
2157
  if(not debug){
1779
2158
    avahi_set_log_function(empty_log);
1780
2159
  }
1781
2160
  
1782
 
  if(interface[0] == '\0'){
1783
 
    struct dirent **direntries;
1784
 
    /* First look for interfaces that are up */
1785
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1786
 
                  alphasort);
1787
 
    if(ret == 0){
1788
 
      /* No up interfaces, look for any good interfaces */
1789
 
      free(direntries);
1790
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1791
 
                    alphasort);
1792
 
    }
1793
 
    if(ret >= 1){
1794
 
      /* Pick the first interface returned */
1795
 
      interface = strdup(direntries[0]->d_name);
1796
 
      if(debug){
1797
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1798
 
      }
1799
 
      if(interface == NULL){
1800
 
        perror_plus("malloc");
1801
 
        free(direntries);
1802
 
        exitcode = EXIT_FAILURE;
1803
 
        goto end;
1804
 
      }
1805
 
      free(direntries);
1806
 
    } else {
1807
 
      free(direntries);
1808
 
      fprintf_plus(stderr, "Could not find a network interface\n");
1809
 
      exitcode = EXIT_FAILURE;
1810
 
      goto end;
1811
 
    }
1812
 
  }
1813
 
  
1814
2161
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1815
2162
     from the signal handler */
1816
2163
  /* Initialize the pseudo-RNG for Avahi */
1817
2164
  srand((unsigned int) time(NULL));
1818
 
  mc.simple_poll = avahi_simple_poll_new();
1819
 
  if(mc.simple_poll == NULL){
 
2165
  simple_poll = avahi_simple_poll_new();
 
2166
  if(simple_poll == NULL){
1820
2167
    fprintf_plus(stderr,
1821
2168
                 "Avahi: Failed to create simple poll object.\n");
1822
2169
    exitcode = EX_UNAVAILABLE;
1886
2233
    }
1887
2234
  }
1888
2235
  
1889
 
  /* If the interface is down, bring it up */
1890
 
  if(strcmp(interface, "none") != 0){
1891
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1892
 
    if(if_index == 0){
1893
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1894
 
      exitcode = EX_UNAVAILABLE;
1895
 
      goto end;
1896
 
    }
1897
 
    
1898
 
    if(quit_now){
1899
 
      goto end;
1900
 
    }
1901
 
    
1902
 
    /* Re-raise priviliges */
1903
 
    errno = 0;
1904
 
    ret = seteuid(0);
1905
 
    if(ret == -1){
1906
 
      perror_plus("seteuid");
1907
 
    }
1908
 
    
1909
 
#ifdef __linux__
1910
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1911
 
       messages about the network interface to mess up the prompt */
1912
 
    ret = klogctl(8, NULL, 5);
1913
 
    bool restore_loglevel = true;
1914
 
    if(ret == -1){
1915
 
      restore_loglevel = false;
1916
 
      perror_plus("klogctl");
1917
 
    }
1918
 
#endif  /* __linux__ */
1919
 
    
1920
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1921
 
    if(sd < 0){
1922
 
      perror_plus("socket");
1923
 
      exitcode = EX_OSERR;
1924
 
#ifdef __linux__
1925
 
      if(restore_loglevel){
1926
 
        ret = klogctl(7, NULL, 0);
1927
 
        if(ret == -1){
1928
 
          perror_plus("klogctl");
1929
 
        }
1930
 
      }
1931
 
#endif  /* __linux__ */
1932
 
      /* Lower privileges */
1933
 
      errno = 0;
1934
 
      ret = seteuid(uid);
1935
 
      if(ret == -1){
1936
 
        perror_plus("seteuid");
1937
 
      }
1938
 
      goto end;
1939
 
    }
1940
 
    strcpy(network.ifr_name, interface);
1941
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1942
 
    if(ret == -1){
1943
 
      perror_plus("ioctl SIOCGIFFLAGS");
1944
 
#ifdef __linux__
1945
 
      if(restore_loglevel){
1946
 
        ret = klogctl(7, NULL, 0);
1947
 
        if(ret == -1){
1948
 
          perror_plus("klogctl");
1949
 
        }
1950
 
      }
1951
 
#endif  /* __linux__ */
1952
 
      exitcode = EX_OSERR;
1953
 
      /* Lower privileges */
1954
 
      errno = 0;
1955
 
      ret = seteuid(uid);
1956
 
      if(ret == -1){
1957
 
        perror_plus("seteuid");
1958
 
      }
1959
 
      goto end;
1960
 
    }
1961
 
    if((network.ifr_flags & IFF_UP) == 0){
1962
 
      network.ifr_flags |= IFF_UP;
1963
 
      take_down_interface = true;
1964
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1965
 
      if(ret == -1){
1966
 
        take_down_interface = false;
1967
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1968
 
        exitcode = EX_OSERR;
1969
 
#ifdef __linux__
1970
 
        if(restore_loglevel){
1971
 
          ret = klogctl(7, NULL, 0);
1972
 
          if(ret == -1){
1973
 
            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;
1974
2283
          }
1975
2284
        }
1976
 
#endif  /* __linux__ */
1977
 
        /* Lower privileges */
1978
 
        errno = 0;
1979
 
        ret = seteuid(uid);
1980
 
        if(ret == -1){
1981
 
          perror_plus("seteuid");
1982
 
        }
1983
 
        goto end;
1984
 
      }
1985
 
    }
1986
 
    /* Sleep checking until interface is running.
1987
 
       Check every 0.25s, up to total time of delay */
1988
 
    for(int i=0; i < delay * 4; i++){
1989
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1990
 
      if(ret == -1){
1991
 
        perror_plus("ioctl SIOCGIFFLAGS");
1992
 
      } else if(network.ifr_flags & IFF_RUNNING){
1993
2285
        break;
1994
2286
      }
1995
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1996
 
      ret = nanosleep(&sleeptime, NULL);
1997
 
      if(ret == -1 and errno != EINTR){
1998
 
        perror_plus("nanosleep");
1999
 
      }
2000
 
    }
2001
 
    if(not take_down_interface){
2002
 
      /* We won't need the socket anymore */
2003
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2004
 
      if(ret == -1){
2005
 
        perror_plus("close");
2006
 
      }
2007
 
    }
2008
 
#ifdef __linux__
2009
 
    if(restore_loglevel){
2010
 
      /* Restores kernel loglevel to default */
2011
 
      ret = klogctl(7, NULL, 0);
2012
 
      if(ret == -1){
2013
 
        perror_plus("klogctl");
2014
 
      }
2015
 
    }
2016
 
#endif  /* __linux__ */
2017
 
    /* Lower privileges */
2018
 
    errno = 0;
2019
 
    /* Lower privileges */
2020
 
    ret = seteuid(uid);
2021
 
    if(ret == -1){
2022
 
      perror_plus("seteuid");
2023
 
    }
 
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);
2024
2314
  }
2025
2315
  
2026
2316
  if(quit_now){
2027
2317
    goto end;
2028
2318
  }
2029
2319
  
2030
 
  ret = init_gnutls_global(pubkey, seckey);
 
2320
  ret = init_gnutls_global(pubkey, seckey, &mc);
2031
2321
  if(ret == -1){
2032
2322
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2033
2323
    exitcode = EX_UNAVAILABLE;
2040
2330
    goto end;
2041
2331
  }
2042
2332
  
2043
 
  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){
2044
2343
    perror_plus("mkdtemp");
2045
2344
    goto end;
2046
2345
  }
2047
 
  tempdir_created = true;
2048
2346
  
2049
2347
  if(quit_now){
2050
2348
    goto end;
2051
2349
  }
2052
2350
  
2053
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
2351
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2054
2352
    fprintf_plus(stderr, "init_gpgme failed\n");
2055
2353
    exitcode = EX_UNAVAILABLE;
2056
2354
    goto end;
2066
2364
    /* Connect directly, do not use Zeroconf */
2067
2365
    /* (Mainly meant for debugging) */
2068
2366
    char *address = strrchr(connect_to, ':');
 
2367
    
2069
2368
    if(address == NULL){
2070
2369
      fprintf_plus(stderr, "No colon in address\n");
2071
2370
      exitcode = EX_USAGE;
2076
2375
      goto end;
2077
2376
    }
2078
2377
    
2079
 
    uint16_t port;
 
2378
    in_port_t port;
2080
2379
    errno = 0;
2081
2380
    tmpmax = strtoimax(address+1, &tmp, 10);
2082
2381
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2083
 
       or tmpmax != (uint16_t)tmpmax){
 
2382
       or tmpmax != (in_port_t)tmpmax){
2084
2383
      fprintf_plus(stderr, "Bad port number\n");
2085
2384
      exitcode = EX_USAGE;
2086
2385
      goto end;
2087
2386
    }
2088
 
  
 
2387
    
2089
2388
    if(quit_now){
2090
2389
      goto end;
2091
2390
    }
2092
2391
    
2093
 
    port = (uint16_t)tmpmax;
 
2392
    port = (in_port_t)tmpmax;
2094
2393
    *address = '\0';
2095
2394
    /* Colon in address indicates IPv6 */
2096
2395
    int af;
2112
2411
    }
2113
2412
    
2114
2413
    while(not quit_now){
2115
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2414
      ret = start_mandos_communication(address, port, if_index, af,
 
2415
                                       &mc);
2116
2416
      if(quit_now or ret == 0){
2117
2417
        break;
2118
2418
      }
2120
2420
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2121
2421
                     (int)retry_interval);
2122
2422
      }
2123
 
      sleep((int)retry_interval);
 
2423
      sleep((unsigned int)retry_interval);
2124
2424
    }
2125
2425
    
2126
 
    if (not quit_now){
 
2426
    if(not quit_now){
2127
2427
      exitcode = EXIT_SUCCESS;
2128
2428
    }
2129
2429
    
2144
2444
    config.publish_domain = 0;
2145
2445
    
2146
2446
    /* Allocate a new server */
2147
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2148
 
                                 (mc.simple_poll), &config, NULL,
2149
 
                                 NULL, &error);
 
2447
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2448
                                 &config, NULL, NULL, &ret_errno);
2150
2449
    
2151
2450
    /* Free the Avahi configuration data */
2152
2451
    avahi_server_config_free(&config);
2155
2454
  /* Check if creating the Avahi server object succeeded */
2156
2455
  if(mc.server == NULL){
2157
2456
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2158
 
                 avahi_strerror(error));
 
2457
                 avahi_strerror(ret_errno));
2159
2458
    exitcode = EX_UNAVAILABLE;
2160
2459
    goto end;
2161
2460
  }
2167
2466
  /* Create the Avahi service browser */
2168
2467
  sb = avahi_s_service_browser_new(mc.server, if_index,
2169
2468
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2170
 
                                   NULL, 0, browse_callback, NULL);
 
2469
                                   NULL, 0, browse_callback,
 
2470
                                   (void *)&mc);
2171
2471
  if(sb == NULL){
2172
2472
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2173
2473
                 avahi_strerror(avahi_server_errno(mc.server)));
2185
2485
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2186
2486
  }
2187
2487
 
2188
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2189
 
                                (int)(retry_interval * 1000));
 
2488
  ret = avahi_loop_with_timeout(simple_poll,
 
2489
                                (int)(retry_interval * 1000), &mc);
2190
2490
  if(debug){
2191
2491
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2192
2492
                 (ret == 0) ? "successfully" : "with error");
2199
2499
  }
2200
2500
  
2201
2501
  /* Cleanup things */
 
2502
  free(mc.interfaces);
 
2503
  
2202
2504
  if(sb != NULL)
2203
2505
    avahi_s_service_browser_free(sb);
2204
2506
  
2205
2507
  if(mc.server != NULL)
2206
2508
    avahi_server_free(mc.server);
2207
2509
  
2208
 
  if(mc.simple_poll != NULL)
2209
 
    avahi_simple_poll_free(mc.simple_poll);
 
2510
  if(simple_poll != NULL)
 
2511
    avahi_simple_poll_free(simple_poll);
2210
2512
  
2211
2513
  if(gnutls_initialized){
2212
2514
    gnutls_certificate_free_credentials(mc.cred);
2229
2531
    }
2230
2532
  }
2231
2533
  
2232
 
  /* Run network hooks */
2233
 
  run_network_hooks("stop", interface, delay);
2234
 
  
2235
 
  /* Re-raise priviliges */
 
2534
  /* Re-raise privileges */
2236
2535
  {
2237
 
    errno = 0;
2238
 
    ret = seteuid(0);
2239
 
    if(ret == -1){
2240
 
      perror_plus("seteuid");
2241
 
    }
2242
 
    
2243
 
    /* Take down the network interface */
2244
 
    if(take_down_interface and geteuid() == 0){
2245
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2246
 
      if(ret == -1){
2247
 
        perror_plus("ioctl SIOCGIFFLAGS");
2248
 
      } else if(network.ifr_flags & IFF_UP){
2249
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2250
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2251
 
        if(ret == -1){
2252
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2253
 
        }
2254
 
      }
2255
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2256
 
      if(ret == -1){
2257
 
        perror_plus("close");
2258
 
      }
2259
 
    }
2260
 
  }
2261
 
  /* Lower privileges permanently */
2262
 
  errno = 0;
2263
 
  ret = setuid(uid);
2264
 
  if(ret == -1){
2265
 
    perror_plus("setuid");
2266
 
  }
 
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);
2267
2571
  
2268
2572
  /* Removes the GPGME temp directory and all files inside */
2269
 
  if(tempdir_created){
 
2573
  if(tempdir != NULL){
2270
2574
    struct dirent **direntries = NULL;
2271
2575
    struct dirent *direntry = NULL;
2272
2576
    int numentries = scandir(tempdir, &direntries, notdotentries,
2273
2577
                             alphasort);
2274
 
    if (numentries > 0){
 
2578
    if(numentries > 0){
2275
2579
      for(int i = 0; i < numentries; i++){
2276
2580
        direntry = direntries[i];
2277
2581
        char *fullname = NULL;
2292
2596
 
2293
2597
    /* need to clean even if 0 because man page doesn't specify */
2294
2598
    free(direntries);
2295
 
    if (numentries == -1){
 
2599
    if(numentries == -1){
2296
2600
      perror_plus("scandir");
2297
2601
    }
2298
2602
    ret = rmdir(tempdir);