/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 at bsnet
  • Date: 2011-12-24 23:07:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111224230717-yd3c0532w0kaviuc
* plugins.d/mandos-client.c (fprintf_plus): Check format string.
  (run_network_hooks): Check for execl() failure.

Show diffs side-by-side

added added

removed removed

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