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