/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

* plugins.d/mandos-client.c (run_network_hooks): New.
  (main): Run run_network_hooks() with "stop" and "start" at
          appropriate places.  Don't lower privileges permanently
          prematurely.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008-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() */
61
61
                                 */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
 
64
#include <assert.h>             /* assert() */
64
65
#include <errno.h>              /* perror(), errno,
65
66
                                   program_invocation_short_name */
66
67
#include <time.h>               /* nanosleep(), time(), sleep() */
72
73
                                */
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause(), _exit() */
 
76
                                   setgid(), pause() */
76
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
86
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
87
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
88
89
                                   WEXITSTATUS(), WTERMSIG() */
89
 
#include <grp.h>                /* setgroups() */
90
 
#include <argz.h>               /* argz_add_sep(), argz_next(),
91
 
                                   argz_delete(), argz_append(),
92
 
                                   argz_stringify(), argz_add(),
93
 
                                   argz_count() */
94
90
 
95
91
#ifdef __linux__
96
92
#include <sys/klog.h>           /* klogctl() */
138
134
static const char sys_class_net[] = "/sys/class/net";
139
135
char *connect_to = NULL;
140
136
const char *hookdir = HOOKDIR;
141
 
uid_t uid = 65534;
142
 
gid_t gid = 65534;
143
137
 
144
138
/* Doubly linked list that need to be circularly linked when used */
145
139
typedef struct server{
146
140
  const char *ip;
147
 
  in_port_t port;
 
141
  uint16_t port;
148
142
  AvahiIfIndex if_index;
149
143
  int af;
150
144
  struct timespec last_seen;
175
169
 
176
170
/* Function to use when printing errors */
177
171
void perror_plus(const char *print_text){
178
 
  int e = errno;
179
172
  fprintf(stderr, "Mandos plugin %s: ",
180
173
          program_invocation_short_name);
181
 
  errno = e;
182
174
  perror(print_text);
183
175
}
184
176
 
185
 
__attribute__((format (gnu_printf, 2, 3)))
186
 
int fprintf_plus(FILE *stream, const char *format, ...){
187
 
  va_list ap;
188
 
  va_start (ap, format);
189
 
  
190
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
191
 
                             program_invocation_short_name));
192
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
193
 
}
194
 
 
195
177
/*
196
178
 * Make additional room in "buffer" for at least BUFFER_SIZE more
197
179
 * bytes. "buffer_capacity" is how much is currently allocated,
210
192
}
211
193
 
212
194
/* Add server to set of servers to retry periodically */
213
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
214
 
                int af){
 
195
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
196
               int af){
215
197
  int ret;
216
198
  server *new_server = malloc(sizeof(server));
217
199
  if(new_server == NULL){
218
200
    perror_plus("malloc");
219
 
    return false;
 
201
    return -1;
220
202
  }
221
203
  *new_server = (server){ .ip = strdup(ip),
222
204
                          .port = port,
224
206
                          .af = af };
225
207
  if(new_server->ip == NULL){
226
208
    perror_plus("strdup");
227
 
    return false;
 
209
    return -1;
228
210
  }
229
211
  /* Special case of first server */
230
212
  if (mc.current_server == NULL){
241
223
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
242
224
  if(ret == -1){
243
225
    perror_plus("clock_gettime");
244
 
    return false;
 
226
    return -1;
245
227
  }
246
 
  return true;
 
228
  return 0;
247
229
}
248
230
 
249
231
/* 
271
253
    
272
254
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
273
255
    if(rc != GPG_ERR_NO_ERROR){
274
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
275
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
257
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
258
              gpgme_strsource(rc), gpgme_strerror(rc));
276
259
      return false;
277
260
    }
278
261
    
279
262
    rc = gpgme_op_import(mc.ctx, pgp_data);
280
263
    if(rc != GPG_ERR_NO_ERROR){
281
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
282
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
265
              "bad gpgme_op_import: %s: %s\n",
 
266
              gpgme_strsource(rc), gpgme_strerror(rc));
283
267
      return false;
284
268
    }
285
269
    
292
276
  }
293
277
  
294
278
  if(debug){
295
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
279
    fprintf(stderr, "Mandos plugin mandos-client: "
 
280
            "Initializing GPGME\n");
296
281
  }
297
282
  
298
283
  /* Init GPGME */
299
284
  gpgme_check_version(NULL);
300
285
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
301
286
  if(rc != GPG_ERR_NO_ERROR){
302
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
303
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
287
    fprintf(stderr, "Mandos plugin mandos-client: "
 
288
            "bad gpgme_engine_check_version: %s: %s\n",
 
289
            gpgme_strsource(rc), gpgme_strerror(rc));
304
290
    return false;
305
291
  }
306
292
  
307
293
  /* Set GPGME home directory for the OpenPGP engine only */
308
294
  rc = gpgme_get_engine_info(&engine_info);
309
295
  if(rc != GPG_ERR_NO_ERROR){
310
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
311
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
296
    fprintf(stderr, "Mandos plugin mandos-client: "
 
297
            "bad gpgme_get_engine_info: %s: %s\n",
 
298
            gpgme_strsource(rc), gpgme_strerror(rc));
312
299
    return false;
313
300
  }
314
301
  while(engine_info != NULL){
320
307
    engine_info = engine_info->next;
321
308
  }
322
309
  if(engine_info == NULL){
323
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
324
 
                 tempdir);
 
310
    fprintf(stderr, "Mandos plugin mandos-client: "
 
311
            "Could not set GPGME home dir to %s\n", tempdir);
325
312
    return false;
326
313
  }
327
314
  
328
315
  /* Create new GPGME "context" */
329
316
  rc = gpgme_new(&(mc.ctx));
330
317
  if(rc != GPG_ERR_NO_ERROR){
331
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
332
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
333
 
                 gpgme_strerror(rc));
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
320
            gpgme_strerror(rc));
334
321
    return false;
335
322
  }
336
323
  
355
342
  ssize_t plaintext_length = 0;
356
343
  
357
344
  if(debug){
358
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
345
    fprintf(stderr, "Mandos plugin mandos-client: "
 
346
            "Trying to decrypt OpenPGP data\n");
359
347
  }
360
348
  
361
349
  /* Create new GPGME data buffer from memory cryptotext */
362
350
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
363
351
                               0);
364
352
  if(rc != GPG_ERR_NO_ERROR){
365
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
366
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
353
    fprintf(stderr, "Mandos plugin mandos-client: "
 
354
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
355
            gpgme_strsource(rc), gpgme_strerror(rc));
367
356
    return -1;
368
357
  }
369
358
  
370
359
  /* Create new empty GPGME data buffer for the plaintext */
371
360
  rc = gpgme_data_new(&dh_plain);
372
361
  if(rc != GPG_ERR_NO_ERROR){
373
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
374
 
                 "bad gpgme_data_new: %s: %s\n",
375
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
362
    fprintf(stderr, "Mandos plugin mandos-client: "
 
363
            "bad gpgme_data_new: %s: %s\n",
 
364
            gpgme_strsource(rc), gpgme_strerror(rc));
376
365
    gpgme_data_release(dh_crypto);
377
366
    return -1;
378
367
  }
381
370
     data buffer */
382
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
383
372
  if(rc != GPG_ERR_NO_ERROR){
384
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
385
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
373
    fprintf(stderr, "Mandos plugin mandos-client: "
 
374
            "bad gpgme_op_decrypt: %s: %s\n",
 
375
            gpgme_strsource(rc), gpgme_strerror(rc));
386
376
    plaintext_length = -1;
387
377
    if(debug){
388
378
      gpgme_decrypt_result_t result;
389
379
      result = gpgme_op_decrypt_result(mc.ctx);
390
380
      if(result == NULL){
391
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
381
        fprintf(stderr, "Mandos plugin mandos-client: "
 
382
                "gpgme_op_decrypt_result failed\n");
392
383
      } else {
393
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
394
 
                     result->unsupported_algorithm);
395
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
396
 
                     result->wrong_key_usage);
 
384
        fprintf(stderr, "Mandos plugin mandos-client: "
 
385
                "Unsupported algorithm: %s\n",
 
386
                result->unsupported_algorithm);
 
387
        fprintf(stderr, "Mandos plugin mandos-client: "
 
388
                "Wrong key usage: %u\n",
 
389
                result->wrong_key_usage);
397
390
        if(result->file_name != NULL){
398
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
391
          fprintf(stderr, "Mandos plugin mandos-client: "
 
392
                  "File name: %s\n", result->file_name);
399
393
        }
400
394
        gpgme_recipient_t recipient;
401
395
        recipient = result->recipients;
402
396
        while(recipient != NULL){
403
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
404
 
                       gpgme_pubkey_algo_name
405
 
                       (recipient->pubkey_algo));
406
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
407
 
          fprintf_plus(stderr, "Secret key available: %s\n",
408
 
                       recipient->status == GPG_ERR_NO_SECKEY
409
 
                       ? "No" : "Yes");
 
397
          fprintf(stderr, "Mandos plugin mandos-client: "
 
398
                  "Public key algorithm: %s\n",
 
399
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
400
          fprintf(stderr, "Mandos plugin mandos-client: "
 
401
                  "Key ID: %s\n", recipient->keyid);
 
402
          fprintf(stderr, "Mandos plugin mandos-client: "
 
403
                  "Secret key available: %s\n",
 
404
                  recipient->status == GPG_ERR_NO_SECKEY
 
405
                  ? "No" : "Yes");
410
406
          recipient = recipient->next;
411
407
        }
412
408
      }
415
411
  }
416
412
  
417
413
  if(debug){
418
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
414
    fprintf(stderr, "Mandos plugin mandos-client: "
 
415
            "Decryption of OpenPGP data succeeded\n");
419
416
  }
420
417
  
421
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
452
449
  }
453
450
  
454
451
  if(debug){
455
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
452
    fprintf(stderr, "Mandos plugin mandos-client: "
 
453
            "Decrypted password is: ");
456
454
    for(ssize_t i = 0; i < plaintext_length; i++){
457
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
458
456
    }
470
468
}
471
469
 
472
470
static const char * safer_gnutls_strerror(int value){
473
 
  const char *ret = gnutls_strerror(value);
 
471
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
472
                                               -Wunreachable-code */
474
473
  if(ret == NULL)
475
474
    ret = "(unknown)";
476
475
  return ret;
479
478
/* GnuTLS log function callback */
480
479
static void debuggnutls(__attribute__((unused)) int level,
481
480
                        const char* string){
482
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
481
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
483
482
}
484
483
 
485
484
static int init_gnutls_global(const char *pubkeyfilename,
487
486
  int ret;
488
487
  
489
488
  if(debug){
490
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
489
    fprintf(stderr, "Mandos plugin mandos-client: "
 
490
            "Initializing GnuTLS\n");
491
491
  }
492
492
  
493
493
  ret = gnutls_global_init();
494
494
  if(ret != GNUTLS_E_SUCCESS){
495
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
496
 
                 safer_gnutls_strerror(ret));
 
495
    fprintf(stderr, "Mandos plugin mandos-client: "
 
496
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
497
497
    return -1;
498
498
  }
499
499
  
508
508
  /* OpenPGP credentials */
509
509
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
510
510
  if(ret != GNUTLS_E_SUCCESS){
511
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
512
 
                 safer_gnutls_strerror(ret));
 
511
    fprintf(stderr, "Mandos plugin mandos-client: "
 
512
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
513
513
    gnutls_global_deinit();
514
514
    return -1;
515
515
  }
516
516
  
517
517
  if(debug){
518
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
519
 
                 " secret key %s as GnuTLS credentials\n",
520
 
                 pubkeyfilename,
521
 
                 seckeyfilename);
 
518
    fprintf(stderr, "Mandos plugin mandos-client: "
 
519
            "Attempting to use OpenPGP public key %s and"
 
520
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
521
            seckeyfilename);
522
522
  }
523
523
  
524
524
  ret = gnutls_certificate_set_openpgp_key_file
525
525
    (mc.cred, pubkeyfilename, seckeyfilename,
526
526
     GNUTLS_OPENPGP_FMT_BASE64);
527
527
  if(ret != GNUTLS_E_SUCCESS){
528
 
    fprintf_plus(stderr,
529
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
530
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
531
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
532
 
                 safer_gnutls_strerror(ret));
 
528
    fprintf(stderr,
 
529
            "Mandos plugin mandos-client: "
 
530
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
531
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
532
    fprintf(stderr, "Mandos plugin mandos-client: "
 
533
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
533
534
    goto globalfail;
534
535
  }
535
536
  
536
537
  /* GnuTLS server initialization */
537
538
  ret = gnutls_dh_params_init(&mc.dh_params);
538
539
  if(ret != GNUTLS_E_SUCCESS){
539
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
540
 
                 " initialization: %s\n",
541
 
                 safer_gnutls_strerror(ret));
 
540
    fprintf(stderr, "Mandos plugin mandos-client: "
 
541
            "Error in GnuTLS DH parameter initialization:"
 
542
            " %s\n", safer_gnutls_strerror(ret));
542
543
    goto globalfail;
543
544
  }
544
545
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
545
546
  if(ret != GNUTLS_E_SUCCESS){
546
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
547
 
                 safer_gnutls_strerror(ret));
 
547
    fprintf(stderr, "Mandos plugin mandos-client: "
 
548
            "Error in GnuTLS prime generation: %s\n",
 
549
            safer_gnutls_strerror(ret));
548
550
    goto globalfail;
549
551
  }
550
552
  
570
572
    }
571
573
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
572
574
  if(ret != GNUTLS_E_SUCCESS){
573
 
    fprintf_plus(stderr,
574
 
                 "Error in GnuTLS session initialization: %s\n",
575
 
                 safer_gnutls_strerror(ret));
 
575
    fprintf(stderr, "Mandos plugin mandos-client: "
 
576
            "Error in GnuTLS session initialization: %s\n",
 
577
            safer_gnutls_strerror(ret));
576
578
  }
577
579
  
578
580
  {
585
587
      }
586
588
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
587
589
    if(ret != GNUTLS_E_SUCCESS){
588
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
589
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
590
 
                   safer_gnutls_strerror(ret));
 
590
      fprintf(stderr, "Mandos plugin mandos-client: "
 
591
              "Syntax error at: %s\n", err);
 
592
      fprintf(stderr, "Mandos plugin mandos-client: "
 
593
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
591
594
      gnutls_deinit(*session);
592
595
      return -1;
593
596
    }
602
605
    }
603
606
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
604
607
  if(ret != GNUTLS_E_SUCCESS){
605
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
606
 
                 safer_gnutls_strerror(ret));
 
608
    fprintf(stderr, "Mandos plugin mandos-client: "
 
609
            "Error setting GnuTLS credentials: %s\n",
 
610
            safer_gnutls_strerror(ret));
607
611
    gnutls_deinit(*session);
608
612
    return -1;
609
613
  }
621
625
                      __attribute__((unused)) const char *txt){}
622
626
 
623
627
/* Called when a Mandos server is found */
624
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
628
static int start_mandos_communication(const char *ip, uint16_t port,
625
629
                                      AvahiIfIndex if_index,
626
630
                                      int af){
627
631
  int ret, tcp_sd = -1;
654
658
    pf = PF_INET;
655
659
    break;
656
660
  default:
657
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
661
    fprintf(stderr, "Mandos plugin mandos-client: "
 
662
            "Bad address family: %d\n", af);
658
663
    errno = EINVAL;
659
664
    return -1;
660
665
  }
665
670
  }
666
671
  
667
672
  if(debug){
668
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
669
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
673
    fprintf(stderr, "Mandos plugin mandos-client: "
 
674
            "Setting up a TCP connection to %s, port %" PRIu16
 
675
            "\n", ip, port);
670
676
  }
671
677
  
672
678
  tcp_sd = socket(pf, SOCK_STREAM, 0);
698
704
  }
699
705
  if(ret == 0){
700
706
    int e = errno;
701
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
707
    fprintf(stderr, "Mandos plugin mandos-client: "
 
708
            "Bad address: %s\n", ip);
702
709
    errno = e;
703
710
    goto mandos_end;
704
711
  }
705
712
  if(af == AF_INET6){
706
 
    to.in6.sin6_port = htons(port);    
 
713
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
714
                                       -Wconversion and
 
715
                                       -Wunreachable-code */
 
716
    
707
717
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
708
718
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
709
719
                                -Wunreachable-code*/
710
720
      if(if_index == AVAHI_IF_UNSPEC){
711
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
712
 
                     " incomplete without a network interface\n");
 
721
        fprintf(stderr, "Mandos plugin mandos-client: "
 
722
                "An IPv6 link-local address is incomplete"
 
723
                " without a network interface\n");
713
724
        errno = EINVAL;
714
725
        goto mandos_end;
715
726
      }
733
744
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
734
745
        perror_plus("if_indextoname");
735
746
      } else {
736
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
737
 
                     "\n", ip, interface, (uintmax_t)port);
 
747
        fprintf(stderr, "Mandos plugin mandos-client: "
 
748
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
749
                ip, interface, port);
738
750
      }
739
751
    } else {
740
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
741
 
                   ip, (uintmax_t)port);
 
752
      fprintf(stderr, "Mandos plugin mandos-client: "
 
753
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
742
754
    }
743
755
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
744
756
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
754
766
      perror_plus("inet_ntop");
755
767
    } else {
756
768
      if(strcmp(addrstr, ip) != 0){
757
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
769
        fprintf(stderr, "Mandos plugin mandos-client: "
 
770
                "Canonical address form: %s\n", addrstr);
758
771
      }
759
772
    }
760
773
  }
814
827
  }
815
828
  
816
829
  if(debug){
817
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
830
    fprintf(stderr, "Mandos plugin mandos-client: "
 
831
            "Establishing TLS session with %s\n", ip);
818
832
  }
819
833
  
820
834
  if(quit_now){
822
836
    goto mandos_end;
823
837
  }
824
838
  
825
 
  /* This casting via intptr_t is to eliminate warning about casting
826
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
827
 
     function "set-session-transport-fd!" does it. */
828
 
  gnutls_transport_set_ptr(session,
829
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
839
  /* Spurious warning from -Wint-to-pointer-cast */
 
840
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
830
841
  
831
842
  if(quit_now){
832
843
    errno = EINTR;
843
854
  
844
855
  if(ret != GNUTLS_E_SUCCESS){
845
856
    if(debug){
846
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
857
      fprintf(stderr, "Mandos plugin mandos-client: "
 
858
              "*** GnuTLS Handshake failed ***\n");
847
859
      gnutls_perror(ret);
848
860
    }
849
861
    errno = EPROTO;
853
865
  /* Read OpenPGP packet that contains the wanted password */
854
866
  
855
867
  if(debug){
856
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
857
 
                 " %s\n", ip);
 
868
    fprintf(stderr, "Mandos plugin mandos-client: "
 
869
            "Retrieving OpenPGP encrypted password from %s\n", ip);
858
870
  }
859
871
  
860
872
  while(true){
898
910
          }
899
911
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
900
912
        if(ret < 0){
901
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
902
 
                       "***\n");
 
913
          fprintf(stderr, "Mandos plugin mandos-client: "
 
914
                  "*** GnuTLS Re-handshake failed ***\n");
903
915
          gnutls_perror(ret);
904
916
          errno = EPROTO;
905
917
          goto mandos_end;
906
918
        }
907
919
        break;
908
920
      default:
909
 
        fprintf_plus(stderr, "Unknown error while reading data from"
910
 
                     " encrypted session with Mandos server\n");
 
921
        fprintf(stderr, "Mandos plugin mandos-client: "
 
922
                "Unknown error while reading data from"
 
923
                " encrypted session with Mandos server\n");
911
924
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
912
925
        errno = EIO;
913
926
        goto mandos_end;
918
931
  }
919
932
  
920
933
  if(debug){
921
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
934
    fprintf(stderr, "Mandos plugin mandos-client: "
 
935
            "Closing TLS session\n");
922
936
  }
923
937
  
924
938
  if(quit_now){
953
967
        if(ret == 0 and ferror(stdout)){
954
968
          int e = errno;
955
969
          if(debug){
956
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
957
 
                         strerror(errno));
 
970
            fprintf(stderr, "Mandos plugin mandos-client: "
 
971
                    "Error writing encrypted data: %s\n",
 
972
                    strerror(errno));
958
973
          }
959
974
          errno = e;
960
975
          goto mandos_end;
1005
1020
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1006
1021
                             flags,
1007
1022
                             AVAHI_GCC_UNUSED void* userdata){
1008
 
  if(r == NULL){
1009
 
    return;
1010
 
  }
 
1023
  assert(r);
1011
1024
  
1012
1025
  /* Called whenever a service has been resolved successfully or
1013
1026
     timed out */
1019
1032
  switch(event){
1020
1033
  default:
1021
1034
  case AVAHI_RESOLVER_FAILURE:
1022
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1023
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1024
 
                 domain,
1025
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1035
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1036
            "(Avahi Resolver) Failed to resolve service '%s'"
 
1037
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
1038
            avahi_strerror(avahi_server_errno(mc.server)));
1026
1039
    break;
1027
1040
    
1028
1041
  case AVAHI_RESOLVER_FOUND:
1030
1043
      char ip[AVAHI_ADDRESS_STR_MAX];
1031
1044
      avahi_address_snprint(ip, sizeof(ip), address);
1032
1045
      if(debug){
1033
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1034
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1035
 
                     host_name, ip, (intmax_t)interface, port);
 
1046
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1047
                "Mandos server \"%s\" found on %s (%s, %"
 
1048
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1049
                ip, (intmax_t)interface, port);
1036
1050
      }
1037
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1038
 
                                           interface,
 
1051
      int ret = start_mandos_communication(ip, port, interface,
1039
1052
                                           avahi_proto_to_af(proto));
1040
1053
      if(ret == 0){
1041
1054
        avahi_simple_poll_quit(mc.simple_poll);
1042
1055
      } else {
1043
 
        if(not add_server(ip, (in_port_t)port, interface,
1044
 
                          avahi_proto_to_af(proto))){
1045
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1046
 
                       " list\n", name);
1047
 
        }
 
1056
        ret = add_server(ip, port, interface,
 
1057
                         avahi_proto_to_af(proto));
1048
1058
      }
1049
1059
    }
1050
1060
  }
1061
1071
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1062
1072
                            flags,
1063
1073
                            AVAHI_GCC_UNUSED void* userdata){
1064
 
  if(b == NULL){
1065
 
    return;
1066
 
  }
 
1074
  assert(b);
1067
1075
  
1068
1076
  /* Called whenever a new services becomes available on the LAN or
1069
1077
     is removed from the LAN */
1076
1084
  default:
1077
1085
  case AVAHI_BROWSER_FAILURE:
1078
1086
    
1079
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1080
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1087
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1088
            "(Avahi browser) %s\n",
 
1089
            avahi_strerror(avahi_server_errno(mc.server)));
1081
1090
    avahi_simple_poll_quit(mc.simple_poll);
1082
1091
    return;
1083
1092
    
1090
1099
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1091
1100
                                    name, type, domain, protocol, 0,
1092
1101
                                    resolve_callback, NULL) == NULL)
1093
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1094
 
                   " %s\n", name,
1095
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1102
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1103
              "Avahi: Failed to resolve service '%s': %s\n",
 
1104
              name, avahi_strerror(avahi_server_errno(mc.server)));
1096
1105
    break;
1097
1106
    
1098
1107
  case AVAHI_BROWSER_REMOVE:
1101
1110
  case AVAHI_BROWSER_ALL_FOR_NOW:
1102
1111
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1103
1112
    if(debug){
1104
 
      fprintf_plus(stderr, "No Mandos server found, still"
1105
 
                   " searching...\n");
 
1113
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1114
              "No Mandos server found, still searching...\n");
1106
1115
    }
1107
1116
    break;
1108
1117
  }
1125
1134
 
1126
1135
bool get_flags(const char *ifname, struct ifreq *ifr){
1127
1136
  int ret;
1128
 
  error_t ret_errno;
1129
1137
  
1130
1138
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1131
1139
  if(s < 0){
1132
 
    ret_errno = errno;
1133
1140
    perror_plus("socket");
1134
 
    errno = ret_errno;
1135
1141
    return false;
1136
1142
  }
1137
1143
  strcpy(ifr->ifr_name, ifname);
1138
1144
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1139
1145
  if(ret == -1){
1140
1146
    if(debug){
1141
 
      ret_errno = errno;
1142
1147
      perror_plus("ioctl SIOCGIFFLAGS");
1143
 
      errno = ret_errno;
1144
1148
    }
1145
1149
    return false;
1146
1150
  }
1152
1156
  /* Reject the loopback device */
1153
1157
  if(ifr->ifr_flags & IFF_LOOPBACK){
1154
1158
    if(debug){
1155
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1156
 
                   ifname);
 
1159
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1160
              "Rejecting loopback interface \"%s\"\n", ifname);
1157
1161
    }
1158
1162
    return false;
1159
1163
  }
1160
1164
  /* Accept point-to-point devices only if connect_to is specified */
1161
1165
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1162
1166
    if(debug){
1163
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1164
 
                   " \"%s\"\n", ifname);
 
1167
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1168
              "Accepting point-to-point interface \"%s\"\n", ifname);
1165
1169
    }
1166
1170
    return true;
1167
1171
  }
1168
1172
  /* Otherwise, reject non-broadcast-capable devices */
1169
1173
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1170
1174
    if(debug){
1171
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1172
 
                   " \"%s\"\n", ifname);
 
1175
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1176
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
1173
1177
    }
1174
1178
    return false;
1175
1179
  }
1176
1180
  /* Reject non-ARP interfaces (including dummy interfaces) */
1177
1181
  if(ifr->ifr_flags & IFF_NOARP){
1178
1182
    if(debug){
1179
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1180
 
                   ifname);
 
1183
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1184
              "Rejecting non-ARP interface \"%s\"\n", ifname);
1181
1185
    }
1182
1186
    return false;
1183
1187
  }
1184
1188
  
1185
1189
  /* Accept this device */
1186
1190
  if(debug){
1187
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1191
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1192
            "Interface \"%s\" is good\n", ifname);
1188
1193
  }
1189
1194
  return true;
1190
1195
}
1202
1207
  struct ifreq ifr;
1203
1208
  if(not get_flags(if_entry->d_name, &ifr)){
1204
1209
    if(debug){
1205
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1206
 
                   "\"%s\"\n", if_entry->d_name);
1207
 
    }
1208
 
    return 0;
1209
 
  }
1210
 
  
1211
 
  if(not good_flags(if_entry->d_name, &ifr)){
1212
 
    return 0;
1213
 
  }
1214
 
  return 1;
1215
 
}
1216
 
 
1217
 
/* 
1218
 
 * This function determines if a network interface is up.
1219
 
 */
1220
 
bool interface_is_up(const char *interface){
1221
 
  struct ifreq ifr;
1222
 
  if(not get_flags(interface, &ifr)){
1223
 
    if(debug){
1224
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1225
 
                   "\"%s\"\n", interface);
1226
 
    }
1227
 
    return false;
1228
 
  }
1229
 
  
1230
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1231
 
}
1232
 
 
1233
 
/* 
1234
 
 * This function determines if a network interface is running
1235
 
 */
1236
 
bool interface_is_running(const char *interface){
1237
 
  struct ifreq ifr;
1238
 
  if(not get_flags(interface, &ifr)){
1239
 
    if(debug){
1240
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1241
 
                   "\"%s\"\n", interface);
1242
 
    }
1243
 
    return false;
1244
 
  }
1245
 
  
1246
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
 
1210
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1211
              "Failed to get flags for interface \"%s\"\n",
 
1212
              if_entry->d_name);
 
1213
    }
 
1214
    return 0;
 
1215
  }
 
1216
  
 
1217
  if(not good_flags(if_entry->d_name, &ifr)){
 
1218
    return 0;
 
1219
  }
 
1220
  return 1;
 
1221
}
 
1222
 
 
1223
/* 
 
1224
 * This function determines if a directory entry in /sys/class/net
 
1225
 * corresponds to an acceptable network device which is up.
 
1226
 * (This function is passed to scandir(3) as a filter function.)
 
1227
 */
 
1228
int up_interface(const struct dirent *if_entry){
 
1229
  if(if_entry->d_name[0] == '.'){
 
1230
    return 0;
 
1231
  }
 
1232
  
 
1233
  struct ifreq ifr;
 
1234
  if(not get_flags(if_entry->d_name, &ifr)){
 
1235
    if(debug){
 
1236
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1237
              "Failed to get flags for interface \"%s\"\n",
 
1238
              if_entry->d_name);
 
1239
    }
 
1240
    return 0;
 
1241
  }
 
1242
  
 
1243
  /* Reject down interfaces */
 
1244
  if(not (ifr.ifr_flags & IFF_UP)){
 
1245
    if(debug){
 
1246
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1247
              "Rejecting down interface \"%s\"\n",
 
1248
              if_entry->d_name);
 
1249
    }
 
1250
    return 0;
 
1251
  }
 
1252
  
 
1253
  /* Reject non-running interfaces */
 
1254
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1255
    if(debug){
 
1256
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1257
              "Rejecting non-running interface \"%s\"\n",
 
1258
              if_entry->d_name);
 
1259
    }
 
1260
    return 0;
 
1261
  }
 
1262
  
 
1263
  if(not good_flags(if_entry->d_name, &ifr)){
 
1264
    return 0;
 
1265
  }
 
1266
  return 1;
1247
1267
}
1248
1268
 
1249
1269
int notdotentries(const struct dirent *direntry){
1275
1295
  if((direntry->d_name)[sret] != '\0'){
1276
1296
    /* Contains non-allowed characters */
1277
1297
    if(debug){
1278
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1279
 
                   direntry->d_name);
 
1298
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1299
              "Ignoring hook \"%s\" with bad name\n",
 
1300
              direntry->d_name);
1280
1301
    }
1281
1302
    return 0;
1282
1303
  }
1298
1319
  if(not (S_ISREG(st.st_mode))){
1299
1320
    /* Not a regular file */
1300
1321
    if(debug){
1301
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1302
 
                   direntry->d_name);
 
1322
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1323
              "Ignoring hook \"%s\" - not a file\n",
 
1324
              direntry->d_name);
1303
1325
    }
1304
1326
    return 0;
1305
1327
  }
1306
1328
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1307
1329
    /* Not executable */
1308
1330
    if(debug){
1309
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1310
 
                   direntry->d_name);
 
1331
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1332
              "Ignoring hook \"%s\" - not executable\n",
 
1333
              direntry->d_name);
1311
1334
    }
1312
1335
    return 0;
1313
1336
  }
1314
 
  if(debug){
1315
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1316
 
                 direntry->d_name);
1317
 
  }
1318
1337
  return 1;
1319
1338
}
1320
1339
 
1327
1346
  while(true){
1328
1347
    if(mc.current_server == NULL){
1329
1348
      if (debug){
1330
 
        fprintf_plus(stderr, "Wait until first server is found."
1331
 
                     " No timeout!\n");
 
1349
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1350
                "Wait until first server is found. No timeout!\n");
1332
1351
      }
1333
1352
      ret = avahi_simple_poll_iterate(s, -1);
1334
1353
    } else {
1335
1354
      if (debug){
1336
 
        fprintf_plus(stderr, "Check current_server if we should run"
1337
 
                     " it, or wait\n");
 
1355
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1356
                "Check current_server if we should run it,"
 
1357
                " or wait\n");
1338
1358
      }
1339
1359
      /* the current time */
1340
1360
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1356
1376
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1357
1377
      
1358
1378
      if (debug){
1359
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1360
 
                     block_time);
 
1379
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1380
                "Blocking for %" PRIdMAX " ms\n", block_time);
1361
1381
      }
1362
1382
      
1363
1383
      if(block_time <= 0){
1390
1410
  }
1391
1411
}
1392
1412
 
1393
 
/* Set effective uid to 0, return errno */
1394
 
error_t raise_privileges(void){
1395
 
  error_t old_errno = errno;
1396
 
  error_t ret_errno = 0;
1397
 
  if(seteuid(0) == -1){
1398
 
    ret_errno = errno;
1399
 
    perror_plus("seteuid");
1400
 
  }
1401
 
  errno = old_errno;
1402
 
  return ret_errno;
1403
 
}
1404
 
 
1405
 
/* Set effective and real user ID to 0.  Return errno. */
1406
 
error_t raise_privileges_permanently(void){
1407
 
  error_t old_errno = errno;
1408
 
  error_t ret_errno = raise_privileges();
1409
 
  if(ret_errno != 0){
1410
 
    errno = old_errno;
1411
 
    return ret_errno;
1412
 
  }
1413
 
  if(setuid(0) == -1){
1414
 
    ret_errno = errno;
1415
 
    perror_plus("seteuid");
1416
 
  }
1417
 
  errno = old_errno;
1418
 
  return ret_errno;
1419
 
}
1420
 
 
1421
 
/* Set effective user ID to unprivileged saved user ID */
1422
 
error_t lower_privileges(void){
1423
 
  error_t old_errno = errno;
1424
 
  error_t ret_errno = 0;
1425
 
  if(seteuid(uid) == -1){
1426
 
    ret_errno = errno;
1427
 
    perror_plus("seteuid");
1428
 
  }
1429
 
  errno = old_errno;
1430
 
  return ret_errno;
1431
 
}
1432
 
 
1433
 
/* Lower privileges permanently */
1434
 
error_t lower_privileges_permanently(void){
1435
 
  error_t old_errno = errno;
1436
 
  error_t ret_errno = 0;
1437
 
  if(setuid(uid) == -1){
1438
 
    ret_errno = errno;
1439
 
    perror_plus("setuid");
1440
 
  }
1441
 
  errno = old_errno;
1442
 
  return ret_errno;
1443
 
}
1444
 
 
1445
1413
bool run_network_hooks(const char *mode, const char *interface,
1446
1414
                       const float delay){
1447
1415
  struct dirent **direntries;
1450
1418
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1451
1419
                         alphasort);
1452
1420
  if(numhooks == -1){
1453
 
    if(errno == ENOENT){
1454
 
      if(debug){
1455
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1456
 
                     " found\n", hookdir);
1457
 
      }
1458
 
    } else {
1459
 
      perror_plus("scandir");
1460
 
    }
 
1421
    perror_plus("scandir");
1461
1422
  } else {
1462
1423
    int devnull = open("/dev/null", O_RDONLY);
1463
1424
    for(int i = 0; i < numhooks; i++){
1464
 
      direntry = direntries[i];
 
1425
      direntry = direntries[0];
1465
1426
      char *fullname = NULL;
1466
1427
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1467
1428
      if(ret < 0){
1468
1429
        perror_plus("asprintf");
1469
1430
        continue;
1470
1431
      }
1471
 
      if(debug){
1472
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1473
 
                     direntry->d_name);
1474
 
      }
1475
1432
      pid_t hook_pid = fork();
1476
1433
      if(hook_pid == 0){
1477
1434
        /* Child */
1478
 
        /* Raise privileges */
1479
 
        raise_privileges_permanently();
1480
 
        /* Set group */
1481
 
        errno = 0;
1482
 
        ret = setgid(0);
1483
 
        if(ret == -1){
1484
 
          perror_plus("setgid");
1485
 
        }
1486
 
        /* Reset supplementary groups */
1487
 
        errno = 0;
1488
 
        ret = setgroups(0, NULL);
1489
 
        if(ret == -1){
1490
 
          perror_plus("setgroups");
1491
 
        }
1492
1435
        dup2(devnull, STDIN_FILENO);
1493
1436
        close(devnull);
1494
1437
        dup2(STDERR_FILENO, STDOUT_FILENO);
1495
1438
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1496
1439
        if(ret == -1){
1497
1440
          perror_plus("setenv");
1498
 
          _exit(EX_OSERR);
 
1441
          return false;
1499
1442
        }
1500
1443
        ret = setenv("DEVICE", interface, 1);
1501
1444
        if(ret == -1){
1502
1445
          perror_plus("setenv");
1503
 
          _exit(EX_OSERR);
 
1446
          return false;
1504
1447
        }
1505
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1448
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1506
1449
        if(ret == -1){
1507
1450
          perror_plus("setenv");
1508
 
          _exit(EX_OSERR);
 
1451
          return false;
1509
1452
        }
1510
1453
        ret = setenv("MODE", mode, 1);
1511
1454
        if(ret == -1){
1512
1455
          perror_plus("setenv");
1513
 
          _exit(EX_OSERR);
 
1456
          return false;
1514
1457
        }
1515
1458
        char *delaystring;
1516
1459
        ret = asprintf(&delaystring, "%f", delay);
1517
1460
        if(ret == -1){
1518
1461
          perror_plus("asprintf");
1519
 
          _exit(EX_OSERR);
 
1462
          return false;
1520
1463
        }
1521
1464
        ret = setenv("DELAY", delaystring, 1);
1522
1465
        if(ret == -1){
1523
1466
          free(delaystring);
1524
1467
          perror_plus("setenv");
1525
 
          _exit(EX_OSERR);
 
1468
          return false;
1526
1469
        }
1527
1470
        free(delaystring);
1528
 
        if(connect_to != NULL){
1529
 
          ret = setenv("CONNECT", connect_to, 1);
1530
 
          if(ret == -1){
1531
 
            perror_plus("setenv");
1532
 
            _exit(EX_OSERR);
1533
 
          }
1534
 
        }
1535
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1536
 
          perror_plus("execl");
1537
 
          _exit(EXIT_FAILURE);
1538
 
        }
 
1471
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1472
        perror_plus("execl");
1539
1473
      } else {
1540
1474
        int status;
1541
1475
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1545
1479
        }
1546
1480
        if(WIFEXITED(status)){
1547
1481
          if(WEXITSTATUS(status) != 0){
1548
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1549
 
                         " with status %d\n", direntry->d_name,
1550
 
                         WEXITSTATUS(status));
 
1482
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1483
                    "Warning: network hook \"%s\" exited"
 
1484
                    " with status %d\n", direntry->d_name,
 
1485
                    WEXITSTATUS(status));
1551
1486
            free(fullname);
1552
1487
            continue;
1553
1488
          }
1554
1489
        } else if(WIFSIGNALED(status)){
1555
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1556
 
                       " signal %d\n", direntry->d_name,
1557
 
                       WTERMSIG(status));
 
1490
          fprintf(stderr, "Mandos plugin mandos-client: "
 
1491
                  "Warning: network hook \"%s\" died by"
 
1492
                  " signal %d\n", direntry->d_name,
 
1493
                  WTERMSIG(status));
1558
1494
          free(fullname);
1559
1495
          continue;
1560
1496
        } else {
1561
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1562
 
                       " crashed\n", direntry->d_name);
 
1497
          fprintf(stderr, "Mandos plugin mandos-client: "
 
1498
                  "Warning: network hook \"%s\" crashed\n",
 
1499
                  direntry->d_name);
1563
1500
          free(fullname);
1564
1501
          continue;
1565
1502
        }
1566
1503
      }
1567
1504
      free(fullname);
1568
 
      if(debug){
1569
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1570
 
                     direntry->d_name);
 
1505
      if(quit_now){
 
1506
        break;
1571
1507
      }
1572
1508
    }
1573
1509
    close(devnull);
1575
1511
  return true;
1576
1512
}
1577
1513
 
1578
 
error_t bring_up_interface(const char *const interface,
1579
 
                           const float delay){
1580
 
  int sd = -1;
1581
 
  error_t old_errno = errno;
1582
 
  error_t ret_errno = 0;
1583
 
  int ret, ret_setflags;
1584
 
  struct ifreq network;
1585
 
  unsigned int if_index = if_nametoindex(interface);
1586
 
  if(if_index == 0){
1587
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1588
 
    errno = old_errno;
1589
 
    return ENXIO;
1590
 
  }
1591
 
  
1592
 
  if(quit_now){
1593
 
    errno = old_errno;
1594
 
    return EINTR;
1595
 
  }
1596
 
  
1597
 
  if(not interface_is_up(interface)){
1598
 
    if(not get_flags(interface, &network) and debug){
1599
 
      ret_errno = errno;
1600
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1601
 
                   "\"%s\"\n", interface);
1602
 
      return ret_errno;
1603
 
    }
1604
 
    network.ifr_flags |= IFF_UP;
1605
 
    
1606
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1607
 
    if(sd < 0){
1608
 
      ret_errno = errno;
1609
 
      perror_plus("socket");
1610
 
      errno = old_errno;
1611
 
      return ret_errno;
1612
 
    }
1613
 
  
1614
 
    if(quit_now){
1615
 
      close(sd);
1616
 
      errno = old_errno;
1617
 
      return EINTR;
1618
 
    }
1619
 
    
1620
 
    if(debug){
1621
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1622
 
                   interface);
1623
 
    }
1624
 
    
1625
 
    /* Raise priviliges */
1626
 
    raise_privileges();
1627
 
    
1628
 
#ifdef __linux__
1629
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1630
 
       messages about the network interface to mess up the prompt */
1631
 
    int ret_linux = klogctl(8, NULL, 5);
1632
 
    bool restore_loglevel = true;
1633
 
    if(ret_linux == -1){
1634
 
      restore_loglevel = false;
1635
 
      perror_plus("klogctl");
1636
 
    }
1637
 
#endif  /* __linux__ */
1638
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1639
 
    ret_errno = errno;
1640
 
#ifdef __linux__
1641
 
    if(restore_loglevel){
1642
 
      ret_linux = klogctl(7, NULL, 0);
1643
 
      if(ret_linux == -1){
1644
 
        perror_plus("klogctl");
1645
 
      }
1646
 
    }
1647
 
#endif  /* __linux__ */
1648
 
    
1649
 
    /* Lower privileges */
1650
 
    lower_privileges();
1651
 
    
1652
 
    /* Close the socket */
1653
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1654
 
    if(ret == -1){
1655
 
      perror_plus("close");
1656
 
    }
1657
 
    
1658
 
    if(ret_setflags == -1){
1659
 
      errno = ret_errno;
1660
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1661
 
      errno = old_errno;
1662
 
      return ret_errno;
1663
 
    }
1664
 
  } else if(debug){
1665
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1666
 
                 interface);
1667
 
  }
1668
 
  
1669
 
  /* Sleep checking until interface is running.
1670
 
     Check every 0.25s, up to total time of delay */
1671
 
  for(int i=0; i < delay * 4; i++){
1672
 
    if(interface_is_running(interface)){
1673
 
      break;
1674
 
    }
1675
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1676
 
    ret = nanosleep(&sleeptime, NULL);
1677
 
    if(ret == -1 and errno != EINTR){
1678
 
      perror_plus("nanosleep");
1679
 
    }
1680
 
  }
1681
 
  
1682
 
  errno = old_errno;
1683
 
  return 0;
1684
 
}
1685
 
 
1686
 
error_t take_down_interface(const char *const interface){
1687
 
  int sd = -1;
1688
 
  error_t old_errno = errno;
1689
 
  error_t ret_errno = 0;
1690
 
  int ret, ret_setflags;
1691
 
  struct ifreq network;
1692
 
  unsigned int if_index = if_nametoindex(interface);
1693
 
  if(if_index == 0){
1694
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1695
 
    errno = old_errno;
1696
 
    return ENXIO;
1697
 
  }
1698
 
  if(interface_is_up(interface)){
1699
 
    if(not get_flags(interface, &network) and debug){
1700
 
      ret_errno = errno;
1701
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1702
 
                   "\"%s\"\n", interface);
1703
 
      return ret_errno;
1704
 
    }
1705
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1706
 
    
1707
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1708
 
    if(sd < 0){
1709
 
      ret_errno = errno;
1710
 
      perror_plus("socket");
1711
 
      errno = old_errno;
1712
 
      return ret_errno;
1713
 
    }
1714
 
    
1715
 
    if(debug){
1716
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1717
 
                   interface);
1718
 
    }
1719
 
    
1720
 
    /* Raise priviliges */
1721
 
    raise_privileges();
1722
 
    
1723
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1724
 
    ret_errno = errno;
1725
 
    
1726
 
    /* Lower privileges */
1727
 
    lower_privileges();
1728
 
    
1729
 
    /* Close the socket */
1730
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1731
 
    if(ret == -1){
1732
 
      perror_plus("close");
1733
 
    }
1734
 
    
1735
 
    if(ret_setflags == -1){
1736
 
      errno = ret_errno;
1737
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1738
 
      errno = old_errno;
1739
 
      return ret_errno;
1740
 
    }
1741
 
  } else if(debug){
1742
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1743
 
                 interface);
1744
 
  }
1745
 
  
1746
 
  errno = old_errno;
1747
 
  return 0;
1748
 
}
1749
 
 
1750
1514
int main(int argc, char *argv[]){
1751
1515
  AvahiSServiceBrowser *sb = NULL;
1752
 
  error_t ret_errno;
 
1516
  int error;
1753
1517
  int ret;
1754
1518
  intmax_t tmpmax;
1755
1519
  char *tmp;
1756
1520
  int exitcode = EXIT_SUCCESS;
1757
 
  char *interfaces = NULL;
1758
 
  size_t interfaces_size = 0;
1759
 
  char *interfaces_to_take_down = NULL;
1760
 
  size_t interfaces_to_take_down_size = 0;
 
1521
  const char *interface = "";
 
1522
  struct ifreq network;
 
1523
  int sd = -1;
 
1524
  bool take_down_interface = false;
 
1525
  uid_t uid;
 
1526
  gid_t gid;
1761
1527
  char tempdir[] = "/tmp/mandosXXXXXX";
1762
1528
  bool tempdir_created = false;
1763
1529
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1764
1530
  const char *seckey = PATHDIR "/" SECKEY;
1765
1531
  const char *pubkey = PATHDIR "/" PUBKEY;
1766
 
  char *interfaces_hooks = NULL;
1767
 
  size_t interfaces_hooks_size = 0;
1768
1532
  
1769
1533
  bool gnutls_initialized = false;
1770
1534
  bool gpgme_initialized = false;
1832
1596
        .group = 2 },
1833
1597
      { .name = "retry", .key = 132,
1834
1598
        .arg = "SECONDS",
1835
 
        .doc = "Retry interval used when denied by the Mandos server",
 
1599
        .doc = "Retry interval used when denied by the mandos server",
1836
1600
        .group = 2 },
1837
1601
      { .name = "network-hook-dir", .key = 133,
1838
1602
        .arg = "DIR",
1861
1625
        connect_to = arg;
1862
1626
        break;
1863
1627
      case 'i':                 /* --interface */
1864
 
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
1865
 
                                 (int)',');
1866
 
        if(ret_errno != 0){
1867
 
          argp_error(state, "%s", strerror(ret_errno));
1868
 
        }
 
1628
        interface = arg;
1869
1629
        break;
1870
1630
      case 's':                 /* --seckey */
1871
1631
        seckey = arg;
1914
1674
        argp_state_help(state, state->out_stream,
1915
1675
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1916
1676
      case 'V':                 /* --version */
1917
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1677
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
 
1678
        fprintf(state->out_stream, "%s\n", argp_program_version);
1918
1679
        exit(argp_err_exit_status);
1919
1680
        break;
1920
1681
      default:
1947
1708
  {
1948
1709
    /* Work around Debian bug #633582:
1949
1710
       <http://bugs.debian.org/633582> */
 
1711
    struct stat st;
1950
1712
    
1951
1713
    /* Re-raise priviliges */
1952
 
    if(raise_privileges() == 0){
1953
 
      struct stat st;
1954
 
      
1955
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1956
 
        int seckey_fd = open(seckey, O_RDONLY);
1957
 
        if(seckey_fd == -1){
1958
 
          perror_plus("open");
1959
 
        } else {
1960
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1961
 
          if(ret == -1){
1962
 
            perror_plus("fstat");
1963
 
          } else {
1964
 
            if(S_ISREG(st.st_mode)
1965
 
               and st.st_uid == 0 and st.st_gid == 0){
1966
 
              ret = fchown(seckey_fd, uid, gid);
1967
 
              if(ret == -1){
1968
 
                perror_plus("fchown");
1969
 
              }
1970
 
            }
1971
 
          }
1972
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1973
 
        }
1974
 
      }
1975
 
    
1976
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1977
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1978
 
        if(pubkey_fd == -1){
1979
 
          perror_plus("open");
1980
 
        } else {
1981
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1982
 
          if(ret == -1){
1983
 
            perror_plus("fstat");
1984
 
          } else {
1985
 
            if(S_ISREG(st.st_mode)
1986
 
               and st.st_uid == 0 and st.st_gid == 0){
1987
 
              ret = fchown(pubkey_fd, uid, gid);
1988
 
              if(ret == -1){
1989
 
                perror_plus("fchown");
1990
 
              }
1991
 
            }
1992
 
          }
1993
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1994
 
        }
1995
 
      }
1996
 
    
1997
 
      /* Lower privileges */
1998
 
      errno = 0;
1999
 
      ret = seteuid(uid);
2000
 
      if(ret == -1){
2001
 
        perror_plus("seteuid");
2002
 
      }
2003
 
    }
2004
 
  }
2005
 
  
2006
 
  /* Remove empty interface names */
2007
 
  {
2008
 
    char *interface = NULL;
2009
 
    while((interface = argz_next(interfaces, interfaces_size,
2010
 
                                 interface))){
2011
 
      if(if_nametoindex(interface) == 0){
2012
 
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2013
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2014
 
                       " \"%s\"\n", interface);
2015
 
        }
2016
 
        argz_delete(&interfaces, &interfaces_size, interface);
2017
 
        interface = NULL;
2018
 
      }
 
1714
    errno = 0;
 
1715
    ret = seteuid(0);
 
1716
    if(ret == -1){
 
1717
      perror_plus("seteuid");
 
1718
    }
 
1719
    
 
1720
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1721
      int seckey_fd = open(seckey, O_RDONLY);
 
1722
      if(seckey_fd == -1){
 
1723
        perror_plus("open");
 
1724
      } else {
 
1725
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1726
        if(ret == -1){
 
1727
          perror_plus("fstat");
 
1728
        } else {
 
1729
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1730
            ret = fchown(seckey_fd, uid, gid);
 
1731
            if(ret == -1){
 
1732
              perror_plus("fchown");
 
1733
            }
 
1734
          }
 
1735
        }
 
1736
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1737
      }
 
1738
    }
 
1739
    
 
1740
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1741
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1742
      if(pubkey_fd == -1){
 
1743
        perror_plus("open");
 
1744
      } else {
 
1745
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1746
        if(ret == -1){
 
1747
          perror_plus("fstat");
 
1748
        } else {
 
1749
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1750
            ret = fchown(pubkey_fd, uid, gid);
 
1751
            if(ret == -1){
 
1752
              perror_plus("fchown");
 
1753
            }
 
1754
          }
 
1755
        }
 
1756
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1757
      }
 
1758
    }
 
1759
    
 
1760
    /* Lower privileges */
 
1761
    errno = 0;
 
1762
    ret = seteuid(uid);
 
1763
    if(ret == -1){
 
1764
      perror_plus("seteuid");
2019
1765
    }
2020
1766
  }
2021
1767
  
2022
1768
  /* Run network hooks */
2023
1769
  {
2024
 
    
2025
 
    if(interfaces != NULL){
2026
 
      interfaces_hooks = malloc(interfaces_size);
2027
 
      if(interfaces_hooks == NULL){
2028
 
        perror_plus("malloc");
2029
 
        goto end;
2030
 
      }
2031
 
      memcpy(interfaces_hooks, interfaces, interfaces_size);
2032
 
      interfaces_hooks_size = interfaces_size;
2033
 
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
2034
 
                     (int)',');
 
1770
    /* Re-raise priviliges */
 
1771
    errno = 0;
 
1772
    ret = seteuid(0);
 
1773
    if(ret == -1){
 
1774
      perror_plus("seteuid");
2035
1775
    }
2036
 
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
2037
 
                             interfaces_hooks : "", delay)){
 
1776
    if(not run_network_hooks("start", interface, delay)){
2038
1777
      goto end;
2039
1778
    }
 
1779
    /* Lower privileges */
 
1780
    errno = 0;
 
1781
    ret = seteuid(uid);
 
1782
    if(ret == -1){
 
1783
      perror_plus("seteuid");
 
1784
    }
2040
1785
  }
2041
1786
  
2042
1787
  if(not debug){
2043
1788
    avahi_set_log_function(empty_log);
2044
1789
  }
2045
1790
  
 
1791
  if(interface[0] == '\0'){
 
1792
    struct dirent **direntries;
 
1793
    /* First look for interfaces that are up */
 
1794
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1795
                  alphasort);
 
1796
    if(ret == 0){
 
1797
      /* No up interfaces, look for any good interfaces */
 
1798
      free(direntries);
 
1799
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1800
                    alphasort);
 
1801
    }
 
1802
    if(ret >= 1){
 
1803
      /* Pick the first interface returned */
 
1804
      interface = strdup(direntries[0]->d_name);
 
1805
      if(debug){
 
1806
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1807
                "Using interface \"%s\"\n", interface);
 
1808
      }
 
1809
      if(interface == NULL){
 
1810
        perror_plus("malloc");
 
1811
        free(direntries);
 
1812
        exitcode = EXIT_FAILURE;
 
1813
        goto end;
 
1814
      }
 
1815
      free(direntries);
 
1816
    } else {
 
1817
      free(direntries);
 
1818
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1819
              "Could not find a network interface\n");
 
1820
      exitcode = EXIT_FAILURE;
 
1821
      goto end;
 
1822
    }
 
1823
  }
 
1824
  
2046
1825
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2047
1826
     from the signal handler */
2048
1827
  /* Initialize the pseudo-RNG for Avahi */
2049
1828
  srand((unsigned int) time(NULL));
2050
1829
  mc.simple_poll = avahi_simple_poll_new();
2051
1830
  if(mc.simple_poll == NULL){
2052
 
    fprintf_plus(stderr,
2053
 
                 "Avahi: Failed to create simple poll object.\n");
 
1831
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1832
            "Avahi: Failed to create simple poll object.\n");
2054
1833
    exitcode = EX_UNAVAILABLE;
2055
1834
    goto end;
2056
1835
  }
2118
1897
    }
2119
1898
  }
2120
1899
  
2121
 
  /* If no interfaces were specified, make a list */
2122
 
  if(interfaces == NULL){
2123
 
    struct dirent **direntries;
2124
 
    /* Look for any good interfaces */
2125
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2126
 
                  alphasort);
2127
 
    if(ret >= 1){
2128
 
      /* Add all found interfaces to interfaces list */
2129
 
      for(int i = 0; i < ret; ++i){
2130
 
        ret_errno = argz_add(&interfaces, &interfaces_size,
2131
 
                             direntries[i]->d_name);
2132
 
        if(ret_errno != 0){
2133
 
          perror_plus("argz_add");
2134
 
          continue;
2135
 
        }
2136
 
        if(debug){
2137
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2138
 
                       direntries[i]->d_name);
2139
 
        }
2140
 
      }
2141
 
      free(direntries);
2142
 
    } else {
2143
 
      free(direntries);
2144
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2145
 
      exitcode = EXIT_FAILURE;
2146
 
      goto end;
2147
 
    }
2148
 
  }
2149
 
  
2150
 
  /* If we only got one interface, explicitly use only that one */
2151
 
  if(argz_count(interfaces, interfaces_size) == 1){
2152
 
    if(debug){
2153
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2154
 
                   interfaces);
2155
 
    }
2156
 
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
2157
 
  }
2158
 
  
2159
 
  /* Bring up interfaces which are down */
2160
 
  if(not (argz_count(interfaces, interfaces_size) == 1
2161
 
          and strcmp(interfaces, "none") == 0)){
2162
 
    char *interface = NULL;
2163
 
    while((interface = argz_next(interfaces, interfaces_size,
2164
 
                                 interface))){
2165
 
      bool interface_was_up = interface_is_up(interface);
2166
 
      ret = bring_up_interface(interface, delay);
2167
 
      if(not interface_was_up){
2168
 
        if(ret != 0){
2169
 
          errno = ret;
2170
 
          perror_plus("Failed to bring up interface");
2171
 
        } else {
2172
 
          ret_errno = argz_add(&interfaces_to_take_down,
2173
 
                               &interfaces_to_take_down_size,
2174
 
                               interface);
2175
 
        }
2176
 
      }
2177
 
    }
2178
 
    free(interfaces);
2179
 
    interfaces = NULL;
2180
 
    interfaces_size = 0;
2181
 
    if(debug and (interfaces_to_take_down == NULL)){
2182
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
1900
  /* If the interface is down, bring it up */
 
1901
  if(strcmp(interface, "none") != 0){
 
1902
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1903
    if(if_index == 0){
 
1904
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1905
              "No such interface: \"%s\"\n", interface);
 
1906
      exitcode = EX_UNAVAILABLE;
 
1907
      goto end;
 
1908
    }
 
1909
    
 
1910
    if(quit_now){
 
1911
      goto end;
 
1912
    }
 
1913
    
 
1914
    /* Re-raise priviliges */
 
1915
    errno = 0;
 
1916
    ret = seteuid(0);
 
1917
    if(ret == -1){
 
1918
      perror_plus("seteuid");
 
1919
    }
 
1920
    
 
1921
#ifdef __linux__
 
1922
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1923
       messages about the network interface to mess up the prompt */
 
1924
    ret = klogctl(8, NULL, 5);
 
1925
    bool restore_loglevel = true;
 
1926
    if(ret == -1){
 
1927
      restore_loglevel = false;
 
1928
      perror_plus("klogctl");
 
1929
    }
 
1930
#endif  /* __linux__ */
 
1931
    
 
1932
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1933
    if(sd < 0){
 
1934
      perror_plus("socket");
 
1935
      exitcode = EX_OSERR;
 
1936
#ifdef __linux__
 
1937
      if(restore_loglevel){
 
1938
        ret = klogctl(7, NULL, 0);
 
1939
        if(ret == -1){
 
1940
          perror_plus("klogctl");
 
1941
        }
 
1942
      }
 
1943
#endif  /* __linux__ */
 
1944
      /* Lower privileges */
 
1945
      errno = 0;
 
1946
      ret = seteuid(uid);
 
1947
      if(ret == -1){
 
1948
        perror_plus("seteuid");
 
1949
      }
 
1950
      goto end;
 
1951
    }
 
1952
    strcpy(network.ifr_name, interface);
 
1953
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1954
    if(ret == -1){
 
1955
      perror_plus("ioctl SIOCGIFFLAGS");
 
1956
#ifdef __linux__
 
1957
      if(restore_loglevel){
 
1958
        ret = klogctl(7, NULL, 0);
 
1959
        if(ret == -1){
 
1960
          perror_plus("klogctl");
 
1961
        }
 
1962
      }
 
1963
#endif  /* __linux__ */
 
1964
      exitcode = EX_OSERR;
 
1965
      /* Lower privileges */
 
1966
      errno = 0;
 
1967
      ret = seteuid(uid);
 
1968
      if(ret == -1){
 
1969
        perror_plus("seteuid");
 
1970
      }
 
1971
      goto end;
 
1972
    }
 
1973
    if((network.ifr_flags & IFF_UP) == 0){
 
1974
      network.ifr_flags |= IFF_UP;
 
1975
      take_down_interface = true;
 
1976
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1977
      if(ret == -1){
 
1978
        take_down_interface = false;
 
1979
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1980
        exitcode = EX_OSERR;
 
1981
#ifdef __linux__
 
1982
        if(restore_loglevel){
 
1983
          ret = klogctl(7, NULL, 0);
 
1984
          if(ret == -1){
 
1985
            perror_plus("klogctl");
 
1986
          }
 
1987
        }
 
1988
#endif  /* __linux__ */
 
1989
        /* Lower privileges */
 
1990
        errno = 0;
 
1991
        ret = seteuid(uid);
 
1992
        if(ret == -1){
 
1993
          perror_plus("seteuid");
 
1994
        }
 
1995
        goto end;
 
1996
      }
 
1997
    }
 
1998
    /* Sleep checking until interface is running.
 
1999
       Check every 0.25s, up to total time of delay */
 
2000
    for(int i=0; i < delay * 4; i++){
 
2001
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2002
      if(ret == -1){
 
2003
        perror_plus("ioctl SIOCGIFFLAGS");
 
2004
      } else if(network.ifr_flags & IFF_RUNNING){
 
2005
        break;
 
2006
      }
 
2007
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
2008
      ret = nanosleep(&sleeptime, NULL);
 
2009
      if(ret == -1 and errno != EINTR){
 
2010
        perror_plus("nanosleep");
 
2011
      }
 
2012
    }
 
2013
    if(not take_down_interface){
 
2014
      /* We won't need the socket anymore */
 
2015
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2016
      if(ret == -1){
 
2017
        perror_plus("close");
 
2018
      }
 
2019
    }
 
2020
#ifdef __linux__
 
2021
    if(restore_loglevel){
 
2022
      /* Restores kernel loglevel to default */
 
2023
      ret = klogctl(7, NULL, 0);
 
2024
      if(ret == -1){
 
2025
        perror_plus("klogctl");
 
2026
      }
 
2027
    }
 
2028
#endif  /* __linux__ */
 
2029
    /* Lower privileges */
 
2030
    errno = 0;
 
2031
    /* Lower privileges */
 
2032
    ret = seteuid(uid);
 
2033
    if(ret == -1){
 
2034
      perror_plus("seteuid");
2183
2035
    }
2184
2036
  }
2185
2037
  
2189
2041
  
2190
2042
  ret = init_gnutls_global(pubkey, seckey);
2191
2043
  if(ret == -1){
2192
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
2044
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2045
            "init_gnutls_global failed\n");
2193
2046
    exitcode = EX_UNAVAILABLE;
2194
2047
    goto end;
2195
2048
  } else {
2211
2064
  }
2212
2065
  
2213
2066
  if(not init_gpgme(pubkey, seckey, tempdir)){
2214
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
2067
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2068
            "init_gpgme failed\n");
2215
2069
    exitcode = EX_UNAVAILABLE;
2216
2070
    goto end;
2217
2071
  } else {
2226
2080
    /* Connect directly, do not use Zeroconf */
2227
2081
    /* (Mainly meant for debugging) */
2228
2082
    char *address = strrchr(connect_to, ':');
2229
 
    
2230
2083
    if(address == NULL){
2231
 
      fprintf_plus(stderr, "No colon in address\n");
 
2084
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2085
              "No colon in address\n");
2232
2086
      exitcode = EX_USAGE;
2233
2087
      goto end;
2234
2088
    }
2237
2091
      goto end;
2238
2092
    }
2239
2093
    
2240
 
    in_port_t port;
 
2094
    uint16_t port;
2241
2095
    errno = 0;
2242
2096
    tmpmax = strtoimax(address+1, &tmp, 10);
2243
2097
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2244
 
       or tmpmax != (in_port_t)tmpmax){
2245
 
      fprintf_plus(stderr, "Bad port number\n");
 
2098
       or tmpmax != (uint16_t)tmpmax){
 
2099
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2100
              "Bad port number\n");
2246
2101
      exitcode = EX_USAGE;
2247
2102
      goto end;
2248
2103
    }
2251
2106
      goto end;
2252
2107
    }
2253
2108
    
2254
 
    port = (in_port_t)tmpmax;
 
2109
    port = (uint16_t)tmpmax;
2255
2110
    *address = '\0';
2256
2111
    /* Colon in address indicates IPv6 */
2257
2112
    int af;
2278
2133
        break;
2279
2134
      }
2280
2135
      if(debug){
2281
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2282
 
                     (int)retry_interval);
 
2136
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2137
                "Retrying in %d seconds\n", (int)retry_interval);
2283
2138
      }
2284
2139
      sleep((int)retry_interval);
2285
2140
    }
2307
2162
    /* Allocate a new server */
2308
2163
    mc.server = avahi_server_new(avahi_simple_poll_get
2309
2164
                                 (mc.simple_poll), &config, NULL,
2310
 
                                 NULL, &ret_errno);
 
2165
                                 NULL, &error);
2311
2166
    
2312
2167
    /* Free the Avahi configuration data */
2313
2168
    avahi_server_config_free(&config);
2315
2170
  
2316
2171
  /* Check if creating the Avahi server object succeeded */
2317
2172
  if(mc.server == NULL){
2318
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2319
 
                 avahi_strerror(ret_errno));
 
2173
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2174
            "Failed to create Avahi server: %s\n",
 
2175
            avahi_strerror(error));
2320
2176
    exitcode = EX_UNAVAILABLE;
2321
2177
    goto end;
2322
2178
  }
2330
2186
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2331
2187
                                   NULL, 0, browse_callback, NULL);
2332
2188
  if(sb == NULL){
2333
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2334
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
2189
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2190
            "Failed to create service browser: %s\n",
 
2191
            avahi_strerror(avahi_server_errno(mc.server)));
2335
2192
    exitcode = EX_UNAVAILABLE;
2336
2193
    goto end;
2337
2194
  }
2343
2200
  /* Run the main loop */
2344
2201
  
2345
2202
  if(debug){
2346
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2203
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2204
            "Starting Avahi loop search\n");
2347
2205
  }
2348
2206
 
2349
2207
  ret = avahi_loop_with_timeout(mc.simple_poll,
2350
2208
                                (int)(retry_interval * 1000));
2351
2209
  if(debug){
2352
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2353
 
                 (ret == 0) ? "successfully" : "with error");
 
2210
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2211
            "avahi_loop_with_timeout exited %s\n",
 
2212
            (ret == 0) ? "successfully" : "with error");
2354
2213
  }
2355
2214
  
2356
2215
 end:
2357
2216
  
2358
2217
  if(debug){
2359
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2218
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2219
            "%s exiting\n", argv[0]);
2360
2220
  }
2361
2221
  
2362
2222
  /* Cleanup things */
2378
2238
  if(gpgme_initialized){
2379
2239
    gpgme_release(mc.ctx);
2380
2240
  }
2381
 
  
 
2241
 
2382
2242
  /* Cleans up the circular linked list of Mandos servers the client
2383
2243
     has seen */
2384
2244
  if(mc.current_server != NULL){
2392
2252
  
2393
2253
  /* Re-raise priviliges */
2394
2254
  {
2395
 
    raise_privileges();
2396
 
    
 
2255
    errno = 0;
 
2256
    ret = seteuid(0);
 
2257
    if(ret == -1){
 
2258
      perror_plus("seteuid");
 
2259
    }
2397
2260
    /* Run network hooks */
2398
 
    run_network_hooks("stop", interfaces_hooks != NULL ?
2399
 
                      interfaces_hooks : "", delay);
 
2261
    if(not run_network_hooks("stop", interface, delay)){
 
2262
      goto end;
 
2263
    }
2400
2264
    
2401
 
    /* Take down the network interfaces which were brought up */
2402
 
    {
2403
 
      char *interface = NULL;
2404
 
      while((interface=argz_next(interfaces_to_take_down,
2405
 
                                 interfaces_to_take_down_size,
2406
 
                                 interface))){
2407
 
        ret_errno = take_down_interface(interface);
2408
 
        if(ret_errno != 0){
2409
 
          errno = ret_errno;
2410
 
          perror_plus("Failed to take down interface");
 
2265
    /* Take down the network interface */
 
2266
    if(take_down_interface and geteuid() == 0){
 
2267
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2268
      if(ret == -1){
 
2269
        perror_plus("ioctl SIOCGIFFLAGS");
 
2270
      } else if(network.ifr_flags & IFF_UP){
 
2271
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2272
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2273
        if(ret == -1){
 
2274
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2411
2275
        }
2412
2276
      }
2413
 
      if(debug and (interfaces_to_take_down == NULL)){
2414
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2415
 
                     " down\n");
 
2277
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2278
      if(ret == -1){
 
2279
        perror_plus("close");
2416
2280
      }
2417
2281
    }
2418
 
    
2419
 
    lower_privileges_permanently();
2420
 
  }
2421
 
  
2422
 
  free(interfaces_to_take_down);
2423
 
  free(interfaces_hooks);
 
2282
  }
 
2283
  /* Lower privileges permanently */
 
2284
  errno = 0;
 
2285
  ret = setuid(uid);
 
2286
  if(ret == -1){
 
2287
    perror_plus("setuid");
 
2288
  }
2424
2289
  
2425
2290
  /* Removes the GPGME temp directory and all files inside */
2426
2291
  if(tempdir_created){
2440
2305
        }
2441
2306
        ret = remove(fullname);
2442
2307
        if(ret == -1){
2443
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2444
 
                       strerror(errno));
 
2308
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2309
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
2445
2310
        }
2446
2311
        free(fullname);
2447
2312
      }