/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: Some white space fixes.
  (runnable_hook): Simplify name rule.  More debug messages.

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() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
 
76
                                   setgid(), pause() */
77
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
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
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
90
 
96
91
#ifdef __linux__
97
92
#include <sys/klog.h>           /* klogctl() */
139
134
static const char sys_class_net[] = "/sys/class/net";
140
135
char *connect_to = NULL;
141
136
const char *hookdir = HOOKDIR;
142
 
uid_t uid = 65534;
143
 
gid_t gid = 65534;
144
137
 
145
138
/* Doubly linked list that need to be circularly linked when used */
146
139
typedef struct server{
176
169
 
177
170
/* Function to use when printing errors */
178
171
void perror_plus(const char *print_text){
179
 
  int e = errno;
180
172
  fprintf(stderr, "Mandos plugin %s: ",
181
173
          program_invocation_short_name);
182
 
  errno = e;
183
174
  perror(print_text);
184
175
}
185
176
 
186
 
__attribute__((format (gnu_printf, 2, 3)))
187
 
int fprintf_plus(FILE *stream, const char *format, ...){
188
 
  va_list ap;
189
 
  va_start (ap, format);
190
 
  
191
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
192
 
                             program_invocation_short_name));
193
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
194
 
}
195
 
 
196
177
/*
197
178
 * Make additional room in "buffer" for at least BUFFER_SIZE more
198
179
 * bytes. "buffer_capacity" is how much is currently allocated,
211
192
}
212
193
 
213
194
/* Add server to set of servers to retry periodically */
214
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
215
 
                int af){
 
195
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
196
               int af){
216
197
  int ret;
217
198
  server *new_server = malloc(sizeof(server));
218
199
  if(new_server == NULL){
219
200
    perror_plus("malloc");
220
 
    return false;
 
201
    return -1;
221
202
  }
222
203
  *new_server = (server){ .ip = strdup(ip),
223
204
                          .port = port,
225
206
                          .af = af };
226
207
  if(new_server->ip == NULL){
227
208
    perror_plus("strdup");
228
 
    return false;
 
209
    return -1;
229
210
  }
230
211
  /* Special case of first server */
231
212
  if (mc.current_server == NULL){
242
223
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
243
224
  if(ret == -1){
244
225
    perror_plus("clock_gettime");
245
 
    return false;
 
226
    return -1;
246
227
  }
247
 
  return true;
 
228
  return 0;
248
229
}
249
230
 
250
231
/* 
272
253
    
273
254
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
274
255
    if(rc != GPG_ERR_NO_ERROR){
275
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
276
 
                   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));
277
259
      return false;
278
260
    }
279
261
    
280
262
    rc = gpgme_op_import(mc.ctx, pgp_data);
281
263
    if(rc != GPG_ERR_NO_ERROR){
282
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
283
 
                   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));
284
267
      return false;
285
268
    }
286
269
    
293
276
  }
294
277
  
295
278
  if(debug){
296
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
279
    fprintf(stderr, "Mandos plugin mandos-client: "
 
280
            "Initializing GPGME\n");
297
281
  }
298
282
  
299
283
  /* Init GPGME */
300
284
  gpgme_check_version(NULL);
301
285
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
302
286
  if(rc != GPG_ERR_NO_ERROR){
303
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
304
 
                 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));
305
290
    return false;
306
291
  }
307
292
  
308
293
  /* Set GPGME home directory for the OpenPGP engine only */
309
294
  rc = gpgme_get_engine_info(&engine_info);
310
295
  if(rc != GPG_ERR_NO_ERROR){
311
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
312
 
                 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));
313
299
    return false;
314
300
  }
315
301
  while(engine_info != NULL){
321
307
    engine_info = engine_info->next;
322
308
  }
323
309
  if(engine_info == NULL){
324
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
325
 
                 tempdir);
 
310
    fprintf(stderr, "Mandos plugin mandos-client: "
 
311
            "Could not set GPGME home dir to %s\n", tempdir);
326
312
    return false;
327
313
  }
328
314
  
329
315
  /* Create new GPGME "context" */
330
316
  rc = gpgme_new(&(mc.ctx));
331
317
  if(rc != GPG_ERR_NO_ERROR){
332
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
333
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
334
 
                 gpgme_strerror(rc));
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
320
            gpgme_strerror(rc));
335
321
    return false;
336
322
  }
337
323
  
356
342
  ssize_t plaintext_length = 0;
357
343
  
358
344
  if(debug){
359
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
345
    fprintf(stderr, "Mandos plugin mandos-client: "
 
346
            "Trying to decrypt OpenPGP data\n");
360
347
  }
361
348
  
362
349
  /* Create new GPGME data buffer from memory cryptotext */
363
350
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
364
351
                               0);
365
352
  if(rc != GPG_ERR_NO_ERROR){
366
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
367
 
                 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));
368
356
    return -1;
369
357
  }
370
358
  
371
359
  /* Create new empty GPGME data buffer for the plaintext */
372
360
  rc = gpgme_data_new(&dh_plain);
373
361
  if(rc != GPG_ERR_NO_ERROR){
374
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
375
 
                 "bad gpgme_data_new: %s: %s\n",
376
 
                 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));
377
365
    gpgme_data_release(dh_crypto);
378
366
    return -1;
379
367
  }
382
370
     data buffer */
383
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
384
372
  if(rc != GPG_ERR_NO_ERROR){
385
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
386
 
                 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));
387
376
    plaintext_length = -1;
388
377
    if(debug){
389
378
      gpgme_decrypt_result_t result;
390
379
      result = gpgme_op_decrypt_result(mc.ctx);
391
380
      if(result == NULL){
392
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
381
        fprintf(stderr, "Mandos plugin mandos-client: "
 
382
                "gpgme_op_decrypt_result failed\n");
393
383
      } else {
394
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
395
 
                     result->unsupported_algorithm);
396
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
397
 
                     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);
398
390
        if(result->file_name != NULL){
399
 
          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);
400
393
        }
401
394
        gpgme_recipient_t recipient;
402
395
        recipient = result->recipients;
403
396
        while(recipient != NULL){
404
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
405
 
                       gpgme_pubkey_algo_name
406
 
                       (recipient->pubkey_algo));
407
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
408
 
          fprintf_plus(stderr, "Secret key available: %s\n",
409
 
                       recipient->status == GPG_ERR_NO_SECKEY
410
 
                       ? "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");
411
406
          recipient = recipient->next;
412
407
        }
413
408
      }
416
411
  }
417
412
  
418
413
  if(debug){
419
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
414
    fprintf(stderr, "Mandos plugin mandos-client: "
 
415
            "Decryption of OpenPGP data succeeded\n");
420
416
  }
421
417
  
422
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
453
449
  }
454
450
  
455
451
  if(debug){
456
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
452
    fprintf(stderr, "Mandos plugin mandos-client: "
 
453
            "Decrypted password is: ");
457
454
    for(ssize_t i = 0; i < plaintext_length; i++){
458
455
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
459
456
    }
481
478
/* GnuTLS log function callback */
482
479
static void debuggnutls(__attribute__((unused)) int level,
483
480
                        const char* string){
484
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
481
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
485
482
}
486
483
 
487
484
static int init_gnutls_global(const char *pubkeyfilename,
489
486
  int ret;
490
487
  
491
488
  if(debug){
492
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
489
    fprintf(stderr, "Mandos plugin mandos-client: "
 
490
            "Initializing GnuTLS\n");
493
491
  }
494
492
  
495
493
  ret = gnutls_global_init();
496
494
  if(ret != GNUTLS_E_SUCCESS){
497
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
498
 
                 safer_gnutls_strerror(ret));
 
495
    fprintf(stderr, "Mandos plugin mandos-client: "
 
496
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
499
497
    return -1;
500
498
  }
501
499
  
510
508
  /* OpenPGP credentials */
511
509
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
512
510
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
514
 
                 safer_gnutls_strerror(ret));
 
511
    fprintf(stderr, "Mandos plugin mandos-client: "
 
512
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
515
513
    gnutls_global_deinit();
516
514
    return -1;
517
515
  }
518
516
  
519
517
  if(debug){
520
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
521
 
                 " secret key %s as GnuTLS credentials\n",
522
 
                 pubkeyfilename,
523
 
                 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);
524
522
  }
525
523
  
526
524
  ret = gnutls_certificate_set_openpgp_key_file
527
525
    (mc.cred, pubkeyfilename, seckeyfilename,
528
526
     GNUTLS_OPENPGP_FMT_BASE64);
529
527
  if(ret != GNUTLS_E_SUCCESS){
530
 
    fprintf_plus(stderr,
531
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
532
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
533
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
534
 
                 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));
535
534
    goto globalfail;
536
535
  }
537
536
  
538
537
  /* GnuTLS server initialization */
539
538
  ret = gnutls_dh_params_init(&mc.dh_params);
540
539
  if(ret != GNUTLS_E_SUCCESS){
541
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
542
 
                 " initialization: %s\n",
543
 
                 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));
544
543
    goto globalfail;
545
544
  }
546
545
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
547
546
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
549
 
                 safer_gnutls_strerror(ret));
 
547
    fprintf(stderr, "Mandos plugin mandos-client: "
 
548
            "Error in GnuTLS prime generation: %s\n",
 
549
            safer_gnutls_strerror(ret));
550
550
    goto globalfail;
551
551
  }
552
552
  
572
572
    }
573
573
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
574
574
  if(ret != GNUTLS_E_SUCCESS){
575
 
    fprintf_plus(stderr,
576
 
                 "Error in GnuTLS session initialization: %s\n",
577
 
                 safer_gnutls_strerror(ret));
 
575
    fprintf(stderr, "Mandos plugin mandos-client: "
 
576
            "Error in GnuTLS session initialization: %s\n",
 
577
            safer_gnutls_strerror(ret));
578
578
  }
579
579
  
580
580
  {
587
587
      }
588
588
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
589
589
    if(ret != GNUTLS_E_SUCCESS){
590
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
591
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
592
 
                   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));
593
594
      gnutls_deinit(*session);
594
595
      return -1;
595
596
    }
604
605
    }
605
606
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
606
607
  if(ret != GNUTLS_E_SUCCESS){
607
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
608
 
                 safer_gnutls_strerror(ret));
 
608
    fprintf(stderr, "Mandos plugin mandos-client: "
 
609
            "Error setting GnuTLS credentials: %s\n",
 
610
            safer_gnutls_strerror(ret));
609
611
    gnutls_deinit(*session);
610
612
    return -1;
611
613
  }
656
658
    pf = PF_INET;
657
659
    break;
658
660
  default:
659
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
661
    fprintf(stderr, "Mandos plugin mandos-client: "
 
662
            "Bad address family: %d\n", af);
660
663
    errno = EINVAL;
661
664
    return -1;
662
665
  }
667
670
  }
668
671
  
669
672
  if(debug){
670
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
671
 
                 PRIu16 "\n", ip, port);
 
673
    fprintf(stderr, "Mandos plugin mandos-client: "
 
674
            "Setting up a TCP connection to %s, port %" PRIu16
 
675
            "\n", ip, port);
672
676
  }
673
677
  
674
678
  tcp_sd = socket(pf, SOCK_STREAM, 0);
700
704
  }
701
705
  if(ret == 0){
702
706
    int e = errno;
703
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
707
    fprintf(stderr, "Mandos plugin mandos-client: "
 
708
            "Bad address: %s\n", ip);
704
709
    errno = e;
705
710
    goto mandos_end;
706
711
  }
713
718
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
714
719
                                -Wunreachable-code*/
715
720
      if(if_index == AVAHI_IF_UNSPEC){
716
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
717
 
                     " 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");
718
724
        errno = EINVAL;
719
725
        goto mandos_end;
720
726
      }
738
744
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
739
745
        perror_plus("if_indextoname");
740
746
      } else {
741
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
742
 
                     "\n", ip, interface, port);
 
747
        fprintf(stderr, "Mandos plugin mandos-client: "
 
748
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
749
                ip, interface, port);
743
750
      }
744
751
    } else {
745
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
746
 
                   ip, port);
 
752
      fprintf(stderr, "Mandos plugin mandos-client: "
 
753
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
747
754
    }
748
755
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
749
756
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
759
766
      perror_plus("inet_ntop");
760
767
    } else {
761
768
      if(strcmp(addrstr, ip) != 0){
762
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
769
        fprintf(stderr, "Mandos plugin mandos-client: "
 
770
                "Canonical address form: %s\n", addrstr);
763
771
      }
764
772
    }
765
773
  }
819
827
  }
820
828
  
821
829
  if(debug){
822
 
    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);
823
832
  }
824
833
  
825
834
  if(quit_now){
827
836
    goto mandos_end;
828
837
  }
829
838
  
830
 
  /* This casting via intptr_t is to eliminate warning about casting
831
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
832
 
     function "set-session-transport-fd!" does it. */
833
 
  gnutls_transport_set_ptr(session,
834
 
                           (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);
835
841
  
836
842
  if(quit_now){
837
843
    errno = EINTR;
848
854
  
849
855
  if(ret != GNUTLS_E_SUCCESS){
850
856
    if(debug){
851
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
857
      fprintf(stderr, "Mandos plugin mandos-client: "
 
858
              "*** GnuTLS Handshake failed ***\n");
852
859
      gnutls_perror(ret);
853
860
    }
854
861
    errno = EPROTO;
858
865
  /* Read OpenPGP packet that contains the wanted password */
859
866
  
860
867
  if(debug){
861
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
862
 
                 " %s\n", ip);
 
868
    fprintf(stderr, "Mandos plugin mandos-client: "
 
869
            "Retrieving OpenPGP encrypted password from %s\n", ip);
863
870
  }
864
871
  
865
872
  while(true){
903
910
          }
904
911
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
905
912
        if(ret < 0){
906
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
907
 
                       "***\n");
 
913
          fprintf(stderr, "Mandos plugin mandos-client: "
 
914
                  "*** GnuTLS Re-handshake failed ***\n");
908
915
          gnutls_perror(ret);
909
916
          errno = EPROTO;
910
917
          goto mandos_end;
911
918
        }
912
919
        break;
913
920
      default:
914
 
        fprintf_plus(stderr, "Unknown error while reading data from"
915
 
                     " 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");
916
924
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
917
925
        errno = EIO;
918
926
        goto mandos_end;
923
931
  }
924
932
  
925
933
  if(debug){
926
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
934
    fprintf(stderr, "Mandos plugin mandos-client: "
 
935
            "Closing TLS session\n");
927
936
  }
928
937
  
929
938
  if(quit_now){
958
967
        if(ret == 0 and ferror(stdout)){
959
968
          int e = errno;
960
969
          if(debug){
961
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
962
 
                         strerror(errno));
 
970
            fprintf(stderr, "Mandos plugin mandos-client: "
 
971
                    "Error writing encrypted data: %s\n",
 
972
                    strerror(errno));
963
973
          }
964
974
          errno = e;
965
975
          goto mandos_end;
1022
1032
  switch(event){
1023
1033
  default:
1024
1034
  case AVAHI_RESOLVER_FAILURE:
1025
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1026
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1027
 
                 domain,
1028
 
                 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)));
1029
1039
    break;
1030
1040
    
1031
1041
  case AVAHI_RESOLVER_FOUND:
1033
1043
      char ip[AVAHI_ADDRESS_STR_MAX];
1034
1044
      avahi_address_snprint(ip, sizeof(ip), address);
1035
1045
      if(debug){
1036
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1037
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1038
 
                     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);
1039
1050
      }
1040
1051
      int ret = start_mandos_communication(ip, port, interface,
1041
1052
                                           avahi_proto_to_af(proto));
1042
1053
      if(ret == 0){
1043
1054
        avahi_simple_poll_quit(mc.simple_poll);
1044
1055
      } else {
1045
 
        if(not add_server(ip, port, interface,
1046
 
                          avahi_proto_to_af(proto))){
1047
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1048
 
                       " list\n", name);
1049
 
        }
 
1056
        ret = add_server(ip, port, interface,
 
1057
                         avahi_proto_to_af(proto));
1050
1058
      }
1051
1059
    }
1052
1060
  }
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
 
bool run_network_hooks(const char *mode, const char *interface,
1446
 
                       const float delay){
1447
 
  struct dirent **direntries;
1448
 
  struct dirent *direntry;
1449
 
  int ret;
1450
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1451
 
                         alphasort);
1452
 
  if(numhooks == -1){
1453
 
    perror_plus("scandir");
1454
 
  } else {
1455
 
    int devnull = open("/dev/null", O_RDONLY);
1456
 
    for(int i = 0; i < numhooks; i++){
1457
 
      direntry = direntries[i];
1458
 
      char *fullname = NULL;
1459
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1460
 
      if(ret < 0){
1461
 
        perror_plus("asprintf");
1462
 
        continue;
1463
 
      }
1464
 
      if(debug){
1465
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1466
 
                     direntry->d_name);
1467
 
      }
1468
 
      pid_t hook_pid = fork();
1469
 
      if(hook_pid == 0){
1470
 
        /* Child */
1471
 
        /* Raise privileges */
1472
 
        raise_privileges_permanently();
1473
 
        /* Set group */
1474
 
        errno = 0;
1475
 
        ret = setgid(0);
1476
 
        if(ret == -1){
1477
 
          perror_plus("setgid");
1478
 
        }
1479
 
        /* Reset supplementary groups */
1480
 
        errno = 0;
1481
 
        ret = setgroups(0, NULL);
1482
 
        if(ret == -1){
1483
 
          perror_plus("setgroups");
1484
 
        }
1485
 
        dup2(devnull, STDIN_FILENO);
1486
 
        close(devnull);
1487
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1488
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1489
 
        if(ret == -1){
1490
 
          perror_plus("setenv");
1491
 
          _exit(EX_OSERR);
1492
 
        }
1493
 
        ret = setenv("DEVICE", interface, 1);
1494
 
        if(ret == -1){
1495
 
          perror_plus("setenv");
1496
 
          _exit(EX_OSERR);
1497
 
        }
1498
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1499
 
        if(ret == -1){
1500
 
          perror_plus("setenv");
1501
 
          _exit(EX_OSERR);
1502
 
        }
1503
 
        ret = setenv("MODE", mode, 1);
1504
 
        if(ret == -1){
1505
 
          perror_plus("setenv");
1506
 
          _exit(EX_OSERR);
1507
 
        }
1508
 
        char *delaystring;
1509
 
        ret = asprintf(&delaystring, "%f", delay);
1510
 
        if(ret == -1){
1511
 
          perror_plus("asprintf");
1512
 
          _exit(EX_OSERR);
1513
 
        }
1514
 
        ret = setenv("DELAY", delaystring, 1);
1515
 
        if(ret == -1){
1516
 
          free(delaystring);
1517
 
          perror_plus("setenv");
1518
 
          _exit(EX_OSERR);
1519
 
        }
1520
 
        free(delaystring);
1521
 
        if(connect_to != NULL){
1522
 
          ret = setenv("CONNECT", connect_to, 1);
1523
 
          if(ret == -1){
1524
 
            perror_plus("setenv");
1525
 
            _exit(EX_OSERR);
1526
 
          }
1527
 
        }
1528
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1529
 
          perror_plus("execl");
1530
 
          _exit(EXIT_FAILURE);
1531
 
        }
1532
 
      } else {
1533
 
        int status;
1534
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1535
 
          perror_plus("waitpid");
1536
 
          free(fullname);
1537
 
          continue;
1538
 
        }
1539
 
        if(WIFEXITED(status)){
1540
 
          if(WEXITSTATUS(status) != 0){
1541
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1542
 
                         " with status %d\n", direntry->d_name,
1543
 
                         WEXITSTATUS(status));
1544
 
            free(fullname);
1545
 
            continue;
1546
 
          }
1547
 
        } else if(WIFSIGNALED(status)){
1548
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1549
 
                       " signal %d\n", direntry->d_name,
1550
 
                       WTERMSIG(status));
1551
 
          free(fullname);
1552
 
          continue;
1553
 
        } else {
1554
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1555
 
                       " crashed\n", direntry->d_name);
1556
 
          free(fullname);
1557
 
          continue;
1558
 
        }
1559
 
      }
1560
 
      free(fullname);
1561
 
      if(debug){
1562
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1563
 
                     direntry->d_name);
1564
 
      }
1565
 
    }
1566
 
    close(devnull);
1567
 
  }
1568
 
  return true;
1569
 
}
1570
 
 
1571
 
error_t bring_up_interface(const char *const interface,
1572
 
                           const float delay){
1573
 
  int sd = -1;
1574
 
  error_t old_errno = errno;
1575
 
  error_t ret_errno = 0;
1576
 
  int ret, ret_setflags;
1577
 
  struct ifreq network;
1578
 
  unsigned int if_index = if_nametoindex(interface);
1579
 
  if(if_index == 0){
1580
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1581
 
    errno = old_errno;
1582
 
    return ENXIO;
1583
 
  }
1584
 
  
1585
 
  if(quit_now){
1586
 
    errno = old_errno;
1587
 
    return EINTR;
1588
 
  }
1589
 
  
1590
 
  if(not interface_is_up(interface)){
1591
 
    if(not get_flags(interface, &network) and debug){
1592
 
      ret_errno = errno;
1593
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1594
 
                   "\"%s\"\n", interface);
1595
 
      return ret_errno;
1596
 
    }
1597
 
    network.ifr_flags |= IFF_UP;
1598
 
    
1599
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1600
 
    if(sd < 0){
1601
 
      ret_errno = errno;
1602
 
      perror_plus("socket");
1603
 
      errno = old_errno;
1604
 
      return ret_errno;
1605
 
    }
1606
 
  
1607
 
    if(quit_now){
1608
 
      close(sd);
1609
 
      errno = old_errno;
1610
 
      return EINTR;
1611
 
    }
1612
 
    
1613
 
    if(debug){
1614
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1615
 
                   interface);
1616
 
    }
1617
 
    
1618
 
    /* Raise priviliges */
1619
 
    raise_privileges();
1620
 
    
1621
 
#ifdef __linux__
1622
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1623
 
       messages about the network interface to mess up the prompt */
1624
 
    int ret_linux = klogctl(8, NULL, 5);
1625
 
    bool restore_loglevel = true;
1626
 
    if(ret_linux == -1){
1627
 
      restore_loglevel = false;
1628
 
      perror_plus("klogctl");
1629
 
    }
1630
 
#endif  /* __linux__ */
1631
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1632
 
    ret_errno = errno;
1633
 
#ifdef __linux__
1634
 
    if(restore_loglevel){
1635
 
      ret_linux = klogctl(7, NULL, 0);
1636
 
      if(ret_linux == -1){
1637
 
        perror_plus("klogctl");
1638
 
      }
1639
 
    }
1640
 
#endif  /* __linux__ */
1641
 
    
1642
 
    /* Lower privileges */
1643
 
    lower_privileges();
1644
 
    
1645
 
    /* Close the socket */
1646
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1647
 
    if(ret == -1){
1648
 
      perror_plus("close");
1649
 
    }
1650
 
    
1651
 
    if(ret_setflags == -1){
1652
 
      errno = ret_errno;
1653
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1654
 
      errno = old_errno;
1655
 
      return ret_errno;
1656
 
    }
1657
 
  } else if(debug){
1658
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1659
 
                 interface);
1660
 
  }
1661
 
  
1662
 
  /* Sleep checking until interface is running.
1663
 
     Check every 0.25s, up to total time of delay */
1664
 
  for(int i=0; i < delay * 4; i++){
1665
 
    if(interface_is_running(interface)){
1666
 
      break;
1667
 
    }
1668
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1669
 
    ret = nanosleep(&sleeptime, NULL);
1670
 
    if(ret == -1 and errno != EINTR){
1671
 
      perror_plus("nanosleep");
1672
 
    }
1673
 
  }
1674
 
  
1675
 
  errno = old_errno;
1676
 
  return 0;
1677
 
}
1678
 
 
1679
 
error_t take_down_interface(const char *const interface){
1680
 
  int sd = -1;
1681
 
  error_t old_errno = errno;
1682
 
  error_t ret_errno = 0;
1683
 
  int ret, ret_setflags;
1684
 
  struct ifreq network;
1685
 
  unsigned int if_index = if_nametoindex(interface);
1686
 
  if(if_index == 0){
1687
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1688
 
    errno = old_errno;
1689
 
    return ENXIO;
1690
 
  }
1691
 
  if(interface_is_up(interface)){
1692
 
    if(not get_flags(interface, &network) and debug){
1693
 
      ret_errno = errno;
1694
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1695
 
                   "\"%s\"\n", interface);
1696
 
      return ret_errno;
1697
 
    }
1698
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1699
 
    
1700
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1701
 
    if(sd < 0){
1702
 
      ret_errno = errno;
1703
 
      perror_plus("socket");
1704
 
      errno = old_errno;
1705
 
      return ret_errno;
1706
 
    }
1707
 
    
1708
 
    if(debug){
1709
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1710
 
                   interface);
1711
 
    }
1712
 
    
1713
 
    /* Raise priviliges */
1714
 
    raise_privileges();
1715
 
    
1716
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1717
 
    ret_errno = errno;
1718
 
    
1719
 
    /* Lower privileges */
1720
 
    lower_privileges();
1721
 
    
1722
 
    /* Close the socket */
1723
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1724
 
    if(ret == -1){
1725
 
      perror_plus("close");
1726
 
    }
1727
 
    
1728
 
    if(ret_setflags == -1){
1729
 
      errno = ret_errno;
1730
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1731
 
      errno = old_errno;
1732
 
      return ret_errno;
1733
 
    }
1734
 
  } else if(debug){
1735
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1736
 
                 interface);
1737
 
  }
1738
 
  
1739
 
  errno = old_errno;
1740
 
  return 0;
1741
 
}
1742
 
 
1743
1413
int main(int argc, char *argv[]){
1744
1414
  AvahiSServiceBrowser *sb = NULL;
1745
 
  error_t ret_errno;
 
1415
  int error;
1746
1416
  int ret;
1747
1417
  intmax_t tmpmax;
1748
1418
  char *tmp;
1749
1419
  int exitcode = EXIT_SUCCESS;
1750
 
  char *interfaces = NULL;
1751
 
  size_t interfaces_size = 0;
1752
 
  char *interfaces_to_take_down = NULL;
1753
 
  size_t interfaces_to_take_down_size = 0;
 
1420
  const char *interface = "";
 
1421
  struct ifreq network;
 
1422
  int sd = -1;
 
1423
  bool take_down_interface = false;
 
1424
  uid_t uid;
 
1425
  gid_t gid;
1754
1426
  char tempdir[] = "/tmp/mandosXXXXXX";
1755
1427
  bool tempdir_created = false;
1756
1428
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1757
1429
  const char *seckey = PATHDIR "/" SECKEY;
1758
1430
  const char *pubkey = PATHDIR "/" PUBKEY;
1759
 
  char *interfaces_hooks = NULL;
1760
 
  size_t interfaces_hooks_size = 0;
1761
1431
  
1762
1432
  bool gnutls_initialized = false;
1763
1433
  bool gpgme_initialized = false;
1825
1495
        .group = 2 },
1826
1496
      { .name = "retry", .key = 132,
1827
1497
        .arg = "SECONDS",
1828
 
        .doc = "Retry interval used when denied by the Mandos server",
 
1498
        .doc = "Retry interval used when denied by the mandos server",
1829
1499
        .group = 2 },
1830
1500
      { .name = "network-hook-dir", .key = 133,
1831
1501
        .arg = "DIR",
1854
1524
        connect_to = arg;
1855
1525
        break;
1856
1526
      case 'i':                 /* --interface */
1857
 
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
1858
 
                                 (int)',');
1859
 
        if(ret_errno != 0){
1860
 
          argp_error(state, "%s", strerror(ret_errno));
1861
 
        }
 
1527
        interface = arg;
1862
1528
        break;
1863
1529
      case 's':                 /* --seckey */
1864
1530
        seckey = arg;
1907
1573
        argp_state_help(state, state->out_stream,
1908
1574
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1909
1575
      case 'V':                 /* --version */
1910
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1576
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
 
1577
        fprintf(state->out_stream, "%s\n", argp_program_version);
1911
1578
        exit(argp_err_exit_status);
1912
1579
        break;
1913
1580
      default:
1940
1607
  {
1941
1608
    /* Work around Debian bug #633582:
1942
1609
       <http://bugs.debian.org/633582> */
 
1610
    struct stat st;
1943
1611
    
1944
1612
    /* Re-raise priviliges */
1945
 
    if(raise_privileges() == 0){
1946
 
      struct stat st;
1947
 
      
1948
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1949
 
        int seckey_fd = open(seckey, O_RDONLY);
1950
 
        if(seckey_fd == -1){
1951
 
          perror_plus("open");
1952
 
        } else {
1953
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1954
 
          if(ret == -1){
1955
 
            perror_plus("fstat");
1956
 
          } else {
1957
 
            if(S_ISREG(st.st_mode)
1958
 
               and st.st_uid == 0 and st.st_gid == 0){
1959
 
              ret = fchown(seckey_fd, uid, gid);
1960
 
              if(ret == -1){
1961
 
                perror_plus("fchown");
1962
 
              }
1963
 
            }
1964
 
          }
1965
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1966
 
        }
1967
 
      }
1968
 
    
1969
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1970
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1971
 
        if(pubkey_fd == -1){
1972
 
          perror_plus("open");
1973
 
        } else {
1974
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1975
 
          if(ret == -1){
1976
 
            perror_plus("fstat");
1977
 
          } else {
1978
 
            if(S_ISREG(st.st_mode)
1979
 
               and st.st_uid == 0 and st.st_gid == 0){
1980
 
              ret = fchown(pubkey_fd, uid, gid);
1981
 
              if(ret == -1){
1982
 
                perror_plus("fchown");
1983
 
              }
1984
 
            }
1985
 
          }
1986
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1987
 
        }
1988
 
      }
1989
 
    
1990
 
      /* Lower privileges */
1991
 
      errno = 0;
1992
 
      ret = seteuid(uid);
1993
 
      if(ret == -1){
1994
 
        perror_plus("seteuid");
1995
 
      }
1996
 
    }
1997
 
  }
1998
 
  
1999
 
  /* Remove empty interface names */
2000
 
  {
2001
 
    char *interface = NULL;
2002
 
    while((interface = argz_next(interfaces, interfaces_size,
2003
 
                                 interface))){
2004
 
      if(if_nametoindex(interface) == 0){
2005
 
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2006
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2007
 
                       " \"%s\"\n", interface);
2008
 
        }
2009
 
        argz_delete(&interfaces, &interfaces_size, interface);
2010
 
        interface = NULL;
2011
 
      }
2012
 
    }
2013
 
  }
2014
 
  
2015
 
  /* Run network hooks */
2016
 
  {
2017
 
    ret_errno = argz_append(&interfaces_hooks, &interfaces_hooks_size,
2018
 
                            interfaces, interfaces_size);
2019
 
    if(ret_errno != 0){
2020
 
      errno = ret_errno;
2021
 
      perror_plus("argz_append");
2022
 
      goto end;
2023
 
    }
2024
 
    argz_stringify(interfaces_hooks, interfaces_hooks_size, (int)',');
2025
 
    if(not run_network_hooks("start", interfaces_hooks, delay)){
2026
 
      goto end;
 
1613
    errno = 0;
 
1614
    ret = seteuid(0);
 
1615
    if(ret == -1){
 
1616
      perror_plus("seteuid");
 
1617
    }
 
1618
    
 
1619
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1620
      int seckey_fd = open(seckey, O_RDONLY);
 
1621
      if(seckey_fd == -1){
 
1622
        perror_plus("open");
 
1623
      } else {
 
1624
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1625
        if(ret == -1){
 
1626
          perror_plus("fstat");
 
1627
        } else {
 
1628
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1629
            ret = fchown(seckey_fd, uid, gid);
 
1630
            if(ret == -1){
 
1631
              perror_plus("fchown");
 
1632
            }
 
1633
          }
 
1634
        }
 
1635
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1636
      }
 
1637
    }
 
1638
    
 
1639
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1640
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1641
      if(pubkey_fd == -1){
 
1642
        perror_plus("open");
 
1643
      } else {
 
1644
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1645
        if(ret == -1){
 
1646
          perror_plus("fstat");
 
1647
        } else {
 
1648
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1649
            ret = fchown(pubkey_fd, uid, gid);
 
1650
            if(ret == -1){
 
1651
              perror_plus("fchown");
 
1652
            }
 
1653
          }
 
1654
        }
 
1655
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1656
      }
 
1657
    }
 
1658
    
 
1659
    /* Lower privileges */
 
1660
    errno = 0;
 
1661
    ret = seteuid(uid);
 
1662
    if(ret == -1){
 
1663
      perror_plus("seteuid");
 
1664
    }
 
1665
  }
 
1666
  
 
1667
  /* Find network hooks and run them */
 
1668
  {
 
1669
    struct dirent **direntries;
 
1670
    struct dirent *direntry;
 
1671
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1672
                           alphasort);
 
1673
    if(numhooks == -1){
 
1674
      perror_plus("scandir");
 
1675
    } else {
 
1676
      int devnull = open("/dev/null", O_RDONLY);
 
1677
      for(int i = 0; i < numhooks; i++){
 
1678
        direntry = direntries[0];
 
1679
        char *fullname = NULL;
 
1680
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1681
        if(ret < 0){
 
1682
          perror_plus("asprintf");
 
1683
          continue;
 
1684
        }
 
1685
        pid_t hook_pid = fork();
 
1686
        if(hook_pid == 0){
 
1687
          /* Child */
 
1688
          dup2(devnull, STDIN_FILENO);
 
1689
          close(devnull);
 
1690
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1691
          ret = setenv("DEVICE", interface, 1);
 
1692
          if(ret == -1){
 
1693
            perror_plus("setenv");
 
1694
            exit(1);
 
1695
          }
 
1696
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1697
          if(ret == -1){
 
1698
            perror_plus("setenv");
 
1699
            exit(1);
 
1700
          }
 
1701
          ret = setenv("MODE", "start", 1);
 
1702
          if(ret == -1){
 
1703
            perror_plus("setenv");
 
1704
            exit(1);
 
1705
          }
 
1706
          char *delaystring;
 
1707
          ret = asprintf(&delaystring, "%f", delay);
 
1708
          if(ret == -1){
 
1709
            perror_plus("asprintf");
 
1710
            exit(1);
 
1711
          }
 
1712
          ret = setenv("DELAY", delaystring, 1);
 
1713
          if(ret == -1){
 
1714
            free(delaystring);
 
1715
            perror_plus("setenv");
 
1716
            exit(1);
 
1717
          }
 
1718
          free(delaystring);
 
1719
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1720
          perror_plus("execl");
 
1721
        } else {
 
1722
          int status;
 
1723
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1724
            perror_plus("waitpid");
 
1725
            free(fullname);
 
1726
            continue;
 
1727
          }
 
1728
          if(WIFEXITED(status)){
 
1729
            if(WEXITSTATUS(status) != 0){
 
1730
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1731
                      "Warning: network hook \"%s\" exited"
 
1732
                      " with status %d\n", direntry->d_name,
 
1733
                      WEXITSTATUS(status));
 
1734
              free(fullname);
 
1735
              continue;
 
1736
            }
 
1737
          } else if(WIFSIGNALED(status)){
 
1738
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1739
                    "Warning: network hook \"%s\" died by"
 
1740
                    " signal %d\n", direntry->d_name,
 
1741
                    WTERMSIG(status));
 
1742
            free(fullname);
 
1743
            continue;
 
1744
          } else {
 
1745
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1746
                    "Warning: network hook \"%s\" crashed\n",
 
1747
                    direntry->d_name);
 
1748
            free(fullname);
 
1749
            continue;
 
1750
          }
 
1751
        }
 
1752
        free(fullname);
 
1753
        if(quit_now){
 
1754
          goto end;
 
1755
        }
 
1756
      }
 
1757
      close(devnull);
2027
1758
    }
2028
1759
  }
2029
1760
  
2031
1762
    avahi_set_log_function(empty_log);
2032
1763
  }
2033
1764
  
 
1765
  if(interface[0] == '\0'){
 
1766
    struct dirent **direntries;
 
1767
    /* First look for interfaces that are up */
 
1768
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1769
                  alphasort);
 
1770
    if(ret == 0){
 
1771
      /* No up interfaces, look for any good interfaces */
 
1772
      free(direntries);
 
1773
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1774
                    alphasort);
 
1775
    }
 
1776
    if(ret >= 1){
 
1777
      /* Pick the first interface returned */
 
1778
      interface = strdup(direntries[0]->d_name);
 
1779
      if(debug){
 
1780
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1781
                "Using interface \"%s\"\n", interface);
 
1782
      }
 
1783
      if(interface == NULL){
 
1784
        perror_plus("malloc");
 
1785
        free(direntries);
 
1786
        exitcode = EXIT_FAILURE;
 
1787
        goto end;
 
1788
      }
 
1789
      free(direntries);
 
1790
    } else {
 
1791
      free(direntries);
 
1792
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1793
              "Could not find a network interface\n");
 
1794
      exitcode = EXIT_FAILURE;
 
1795
      goto end;
 
1796
    }
 
1797
  }
 
1798
  
2034
1799
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2035
1800
     from the signal handler */
2036
1801
  /* Initialize the pseudo-RNG for Avahi */
2037
1802
  srand((unsigned int) time(NULL));
2038
1803
  mc.simple_poll = avahi_simple_poll_new();
2039
1804
  if(mc.simple_poll == NULL){
2040
 
    fprintf_plus(stderr,
2041
 
                 "Avahi: Failed to create simple poll object.\n");
 
1805
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1806
            "Avahi: Failed to create simple poll object.\n");
2042
1807
    exitcode = EX_UNAVAILABLE;
2043
1808
    goto end;
2044
1809
  }
2106
1871
    }
2107
1872
  }
2108
1873
  
2109
 
  /* If no interfaces were specified, make a list */
2110
 
  if(interfaces == NULL){
2111
 
    struct dirent **direntries;
2112
 
    /* Look for any good interfaces */
2113
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2114
 
                  alphasort);
2115
 
    if(ret >= 1){
2116
 
      /* Add all found interfaces to interfaces list */
2117
 
      for(int i = 0; i < ret; ++i){
2118
 
        ret_errno = argz_add(&interfaces, &interfaces_size,
2119
 
                             direntries[i]->d_name);
2120
 
        if(ret_errno != 0){
2121
 
          perror_plus("argz_add");
2122
 
          continue;
2123
 
        }
2124
 
        if(debug){
2125
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2126
 
                       direntries[i]->d_name);
2127
 
        }
2128
 
      }
2129
 
      free(direntries);
 
1874
  /* If the interface is down, bring it up */
 
1875
  if(strcmp(interface, "none") != 0){
 
1876
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1877
    if(if_index == 0){
 
1878
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1879
              "No such interface: \"%s\"\n", interface);
 
1880
      exitcode = EX_UNAVAILABLE;
 
1881
      goto end;
 
1882
    }
 
1883
    
 
1884
    if(quit_now){
 
1885
      goto end;
 
1886
    }
 
1887
    
 
1888
    /* Re-raise priviliges */
 
1889
    errno = 0;
 
1890
    ret = seteuid(0);
 
1891
    if(ret == -1){
 
1892
      perror_plus("seteuid");
 
1893
    }
 
1894
    
 
1895
#ifdef __linux__
 
1896
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1897
       messages about the network interface to mess up the prompt */
 
1898
    ret = klogctl(8, NULL, 5);
 
1899
    bool restore_loglevel = true;
 
1900
    if(ret == -1){
 
1901
      restore_loglevel = false;
 
1902
      perror_plus("klogctl");
 
1903
    }
 
1904
#endif  /* __linux__ */
 
1905
    
 
1906
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1907
    if(sd < 0){
 
1908
      perror_plus("socket");
 
1909
      exitcode = EX_OSERR;
 
1910
#ifdef __linux__
 
1911
      if(restore_loglevel){
 
1912
        ret = klogctl(7, NULL, 0);
 
1913
        if(ret == -1){
 
1914
          perror_plus("klogctl");
 
1915
        }
 
1916
      }
 
1917
#endif  /* __linux__ */
 
1918
      /* Lower privileges */
 
1919
      errno = 0;
 
1920
      ret = seteuid(uid);
 
1921
      if(ret == -1){
 
1922
        perror_plus("seteuid");
 
1923
      }
 
1924
      goto end;
 
1925
    }
 
1926
    strcpy(network.ifr_name, interface);
 
1927
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1928
    if(ret == -1){
 
1929
      perror_plus("ioctl SIOCGIFFLAGS");
 
1930
#ifdef __linux__
 
1931
      if(restore_loglevel){
 
1932
        ret = klogctl(7, NULL, 0);
 
1933
        if(ret == -1){
 
1934
          perror_plus("klogctl");
 
1935
        }
 
1936
      }
 
1937
#endif  /* __linux__ */
 
1938
      exitcode = EX_OSERR;
 
1939
      /* Lower privileges */
 
1940
      errno = 0;
 
1941
      ret = seteuid(uid);
 
1942
      if(ret == -1){
 
1943
        perror_plus("seteuid");
 
1944
      }
 
1945
      goto end;
 
1946
    }
 
1947
    if((network.ifr_flags & IFF_UP) == 0){
 
1948
      network.ifr_flags |= IFF_UP;
 
1949
      take_down_interface = true;
 
1950
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1951
      if(ret == -1){
 
1952
        take_down_interface = false;
 
1953
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1954
        exitcode = EX_OSERR;
 
1955
#ifdef __linux__
 
1956
        if(restore_loglevel){
 
1957
          ret = klogctl(7, NULL, 0);
 
1958
          if(ret == -1){
 
1959
            perror_plus("klogctl");
 
1960
          }
 
1961
        }
 
1962
#endif  /* __linux__ */
 
1963
        /* Lower privileges */
 
1964
        errno = 0;
 
1965
        ret = seteuid(uid);
 
1966
        if(ret == -1){
 
1967
          perror_plus("seteuid");
 
1968
        }
 
1969
        goto end;
 
1970
      }
 
1971
    }
 
1972
    /* Sleep checking until interface is running.
 
1973
       Check every 0.25s, up to total time of delay */
 
1974
    for(int i=0; i < delay * 4; i++){
 
1975
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1976
      if(ret == -1){
 
1977
        perror_plus("ioctl SIOCGIFFLAGS");
 
1978
      } else if(network.ifr_flags & IFF_RUNNING){
 
1979
        break;
 
1980
      }
 
1981
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1982
      ret = nanosleep(&sleeptime, NULL);
 
1983
      if(ret == -1 and errno != EINTR){
 
1984
        perror_plus("nanosleep");
 
1985
      }
 
1986
    }
 
1987
    if(not take_down_interface){
 
1988
      /* We won't need the socket anymore */
 
1989
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1990
      if(ret == -1){
 
1991
        perror_plus("close");
 
1992
      }
 
1993
    }
 
1994
#ifdef __linux__
 
1995
    if(restore_loglevel){
 
1996
      /* Restores kernel loglevel to default */
 
1997
      ret = klogctl(7, NULL, 0);
 
1998
      if(ret == -1){
 
1999
        perror_plus("klogctl");
 
2000
      }
 
2001
    }
 
2002
#endif  /* __linux__ */
 
2003
    /* Lower privileges */
 
2004
    errno = 0;
 
2005
    if(take_down_interface){
 
2006
      /* Lower privileges */
 
2007
      ret = seteuid(uid);
 
2008
      if(ret == -1){
 
2009
        perror_plus("seteuid");
 
2010
      }
2130
2011
    } else {
2131
 
      free(direntries);
2132
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2133
 
      exitcode = EXIT_FAILURE;
2134
 
      goto end;
2135
 
    }
2136
 
  }
2137
 
  
2138
 
  /* If we only got one interface, explicitly use only that one */
2139
 
  if(argz_count(interfaces, interfaces_size) == 1){
2140
 
    if(debug){
2141
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2142
 
                   interfaces);
2143
 
    }
2144
 
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
2145
 
  }
2146
 
  
2147
 
  /* Bring up interfaces which are down */
2148
 
  if(not (argz_count(interfaces, interfaces_size) == 1
2149
 
          and strcmp(interfaces, "none") == 0)){
2150
 
    char *interface = NULL;
2151
 
    while((interface = argz_next(interfaces, interfaces_size,
2152
 
                                 interface))){
2153
 
      bool interface_was_up = interface_is_up(interface);
2154
 
      ret = bring_up_interface(interface, delay);
2155
 
      if(not interface_was_up){
2156
 
        if(ret != 0){
2157
 
          errno = ret;
2158
 
          perror_plus("Failed to bring up interface");
2159
 
        } else {
2160
 
          ret_errno = argz_add(&interfaces_to_take_down,
2161
 
                               &interfaces_to_take_down_size,
2162
 
                               interface);
2163
 
        }
 
2012
      /* Lower privileges permanently */
 
2013
      ret = setuid(uid);
 
2014
      if(ret == -1){
 
2015
        perror_plus("setuid");
2164
2016
      }
2165
2017
    }
2166
 
    free(interfaces);
2167
 
    interfaces = NULL;
2168
 
    interfaces_size = 0;
2169
 
    if(debug and (interfaces_to_take_down == NULL)){
2170
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2171
 
    }
2172
2018
  }
2173
2019
  
2174
2020
  if(quit_now){
2177
2023
  
2178
2024
  ret = init_gnutls_global(pubkey, seckey);
2179
2025
  if(ret == -1){
2180
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
2026
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2027
            "init_gnutls_global failed\n");
2181
2028
    exitcode = EX_UNAVAILABLE;
2182
2029
    goto end;
2183
2030
  } else {
2199
2046
  }
2200
2047
  
2201
2048
  if(not init_gpgme(pubkey, seckey, tempdir)){
2202
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
2049
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2050
            "init_gpgme failed\n");
2203
2051
    exitcode = EX_UNAVAILABLE;
2204
2052
    goto end;
2205
2053
  } else {
2214
2062
    /* Connect directly, do not use Zeroconf */
2215
2063
    /* (Mainly meant for debugging) */
2216
2064
    char *address = strrchr(connect_to, ':');
2217
 
    
2218
2065
    if(address == NULL){
2219
 
      fprintf_plus(stderr, "No colon in address\n");
 
2066
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2067
              "No colon in address\n");
2220
2068
      exitcode = EX_USAGE;
2221
2069
      goto end;
2222
2070
    }
2230
2078
    tmpmax = strtoimax(address+1, &tmp, 10);
2231
2079
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2232
2080
       or tmpmax != (uint16_t)tmpmax){
2233
 
      fprintf_plus(stderr, "Bad port number\n");
 
2081
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2082
              "Bad port number\n");
2234
2083
      exitcode = EX_USAGE;
2235
2084
      goto end;
2236
2085
    }
2266
2115
        break;
2267
2116
      }
2268
2117
      if(debug){
2269
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2270
 
                     (int)retry_interval);
 
2118
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2119
                "Retrying in %d seconds\n", (int)retry_interval);
2271
2120
      }
2272
2121
      sleep((int)retry_interval);
2273
2122
    }
2295
2144
    /* Allocate a new server */
2296
2145
    mc.server = avahi_server_new(avahi_simple_poll_get
2297
2146
                                 (mc.simple_poll), &config, NULL,
2298
 
                                 NULL, &ret_errno);
 
2147
                                 NULL, &error);
2299
2148
    
2300
2149
    /* Free the Avahi configuration data */
2301
2150
    avahi_server_config_free(&config);
2303
2152
  
2304
2153
  /* Check if creating the Avahi server object succeeded */
2305
2154
  if(mc.server == NULL){
2306
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2307
 
                 avahi_strerror(ret_errno));
 
2155
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2156
            "Failed to create Avahi server: %s\n",
 
2157
            avahi_strerror(error));
2308
2158
    exitcode = EX_UNAVAILABLE;
2309
2159
    goto end;
2310
2160
  }
2318
2168
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2319
2169
                                   NULL, 0, browse_callback, NULL);
2320
2170
  if(sb == NULL){
2321
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2322
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
2171
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2172
            "Failed to create service browser: %s\n",
 
2173
            avahi_strerror(avahi_server_errno(mc.server)));
2323
2174
    exitcode = EX_UNAVAILABLE;
2324
2175
    goto end;
2325
2176
  }
2331
2182
  /* Run the main loop */
2332
2183
  
2333
2184
  if(debug){
2334
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2185
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2186
            "Starting Avahi loop search\n");
2335
2187
  }
2336
2188
 
2337
2189
  ret = avahi_loop_with_timeout(mc.simple_poll,
2338
2190
                                (int)(retry_interval * 1000));
2339
2191
  if(debug){
2340
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2341
 
                 (ret == 0) ? "successfully" : "with error");
 
2192
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2193
            "avahi_loop_with_timeout exited %s\n",
 
2194
            (ret == 0) ? "successfully" : "with error");
2342
2195
  }
2343
2196
  
2344
2197
 end:
2345
2198
  
2346
2199
  if(debug){
2347
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2200
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2201
            "%s exiting\n", argv[0]);
2348
2202
  }
2349
2203
  
2350
2204
  /* Cleanup things */
2366
2220
  if(gpgme_initialized){
2367
2221
    gpgme_release(mc.ctx);
2368
2222
  }
2369
 
  
 
2223
 
2370
2224
  /* Cleans up the circular linked list of Mandos servers the client
2371
2225
     has seen */
2372
2226
  if(mc.current_server != NULL){
2378
2232
    }
2379
2233
  }
2380
2234
  
2381
 
  /* Re-raise priviliges */
2382
 
  {
2383
 
    raise_privileges();
2384
 
    
2385
 
    /* Run network hooks */
2386
 
    run_network_hooks("stop", interfaces_hooks, delay);
2387
 
    
2388
 
    /* Take down the network interfaces which were brought up */
2389
 
    {
2390
 
      char *interface = NULL;
2391
 
      while((interface=argz_next(interfaces_to_take_down,
2392
 
                                 interfaces_to_take_down_size,
2393
 
                                 interface))){
2394
 
        ret_errno = take_down_interface(interface);
2395
 
        if(ret_errno != 0){
2396
 
          errno = ret_errno;
2397
 
          perror_plus("Failed to take down interface");
 
2235
  /* XXX run network hooks "stop" here  */
 
2236
  
 
2237
  /* Take down the network interface */
 
2238
  if(take_down_interface){
 
2239
    /* Re-raise priviliges */
 
2240
    errno = 0;
 
2241
    ret = seteuid(0);
 
2242
    if(ret == -1){
 
2243
      perror_plus("seteuid");
 
2244
    }
 
2245
    if(geteuid() == 0){
 
2246
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2247
      if(ret == -1){
 
2248
        perror_plus("ioctl SIOCGIFFLAGS");
 
2249
      } else if(network.ifr_flags & IFF_UP){
 
2250
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2251
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2252
        if(ret == -1){
 
2253
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2398
2254
        }
2399
2255
      }
2400
 
      if(debug and (interfaces_to_take_down == NULL)){
2401
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2402
 
                     " down\n");
 
2256
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2257
      if(ret == -1){
 
2258
        perror_plus("close");
 
2259
      }
 
2260
      /* Lower privileges permanently */
 
2261
      errno = 0;
 
2262
      ret = setuid(uid);
 
2263
      if(ret == -1){
 
2264
        perror_plus("setuid");
2403
2265
      }
2404
2266
    }
2405
 
    
2406
 
    lower_privileges_permanently();
2407
2267
  }
2408
2268
  
2409
 
  free(interfaces_to_take_down);
2410
 
  free(interfaces_hooks);
2411
 
  
2412
2269
  /* Removes the GPGME temp directory and all files inside */
2413
2270
  if(tempdir_created){
2414
2271
    struct dirent **direntries = NULL;
2427
2284
        }
2428
2285
        ret = remove(fullname);
2429
2286
        if(ret == -1){
2430
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2431
 
                       strerror(errno));
 
2287
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2288
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
2432
2289
        }
2433
2290
        free(fullname);
2434
2291
      }