/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

* Makefile (DOCBOOKTOMAN): Also check manual pages for warnings.
* debian/control (Build-Depends): Added "man".

Show diffs side-by-side

added added

removed removed

Lines of Context:
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
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
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
88
 
91
89
#ifdef __linux__
92
90
#include <sys/klog.h>           /* klogctl() */
110
108
                                   init_gnutls_session(),
111
109
                                   GNUTLS_* */
112
110
#include <gnutls/openpgp.h>
113
 
                         /* gnutls_certificate_set_openpgp_key_file(),
114
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
 
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
115
113
 
116
114
/* GPGME */
117
115
#include <gpgme.h>              /* All GPGME types, constants and
125
123
#define PATHDIR "/conf/conf.d/mandos"
126
124
#define SECKEY "seckey.txt"
127
125
#define PUBKEY "pubkey.txt"
128
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
129
126
 
130
127
bool debug = false;
131
128
static const char mandos_protocol_version[] = "1";
133
130
const char *argp_program_bug_address = "<mandos@recompile.se>";
134
131
static const char sys_class_net[] = "/sys/class/net";
135
132
char *connect_to = NULL;
136
 
const char *hookdir = HOOKDIR;
137
133
 
138
134
/* Doubly linked list that need to be circularly linked when used */
139
135
typedef struct server{
174
170
  perror(print_text);
175
171
}
176
172
 
177
 
int fprintf_plus(FILE *stream, const char *format, ...){
178
 
  va_list ap;
179
 
  va_start (ap, format);
180
 
  
181
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
182
 
                             program_invocation_short_name));
183
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
184
 
}
185
 
 
186
173
/*
187
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
188
175
 * bytes. "buffer_capacity" is how much is currently allocated,
189
176
 * "buffer_length" is how much is already used.
190
177
 */
191
178
size_t incbuffer(char **buffer, size_t buffer_length,
192
 
                 size_t buffer_capacity){
 
179
                  size_t buffer_capacity){
193
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
194
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
195
182
    if(buffer == NULL){
201
188
}
202
189
 
203
190
/* Add server to set of servers to retry periodically */
204
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
205
 
               int af){
 
191
int add_server(const char *ip, uint16_t port,
 
192
                 AvahiIfIndex if_index,
 
193
                 int af){
206
194
  int ret;
207
195
  server *new_server = malloc(sizeof(server));
208
196
  if(new_server == NULL){
210
198
    return -1;
211
199
  }
212
200
  *new_server = (server){ .ip = strdup(ip),
213
 
                          .port = port,
214
 
                          .if_index = if_index,
215
 
                          .af = af };
 
201
                         .port = port,
 
202
                         .if_index = if_index,
 
203
                         .af = af };
216
204
  if(new_server->ip == NULL){
217
205
    perror_plus("strdup");
218
206
    return -1;
240
228
/* 
241
229
 * Initialize GPGME.
242
230
 */
243
 
static bool init_gpgme(const char *seckey, const char *pubkey,
244
 
                       const char *tempdir){
 
231
static bool init_gpgme(const char *seckey,
 
232
                       const char *pubkey, const char *tempdir){
245
233
  gpgme_error_t rc;
246
234
  gpgme_engine_info_t engine_info;
247
235
  
262
250
    
263
251
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
264
252
    if(rc != GPG_ERR_NO_ERROR){
265
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
266
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
253
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
254
              gpgme_strsource(rc), gpgme_strerror(rc));
267
255
      return false;
268
256
    }
269
257
    
270
258
    rc = gpgme_op_import(mc.ctx, pgp_data);
271
259
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
273
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
260
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
261
              gpgme_strsource(rc), gpgme_strerror(rc));
274
262
      return false;
275
263
    }
276
264
    
283
271
  }
284
272
  
285
273
  if(debug){
286
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
274
    fprintf(stderr, "Initializing GPGME\n");
287
275
  }
288
276
  
289
277
  /* Init GPGME */
290
278
  gpgme_check_version(NULL);
291
279
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
292
280
  if(rc != GPG_ERR_NO_ERROR){
293
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
294
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
281
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
282
            gpgme_strsource(rc), gpgme_strerror(rc));
295
283
    return false;
296
284
  }
297
285
  
298
286
  /* Set GPGME home directory for the OpenPGP engine only */
299
287
  rc = gpgme_get_engine_info(&engine_info);
300
288
  if(rc != GPG_ERR_NO_ERROR){
301
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
302
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
289
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
290
            gpgme_strsource(rc), gpgme_strerror(rc));
303
291
    return false;
304
292
  }
305
293
  while(engine_info != NULL){
311
299
    engine_info = engine_info->next;
312
300
  }
313
301
  if(engine_info == NULL){
314
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
315
 
                 tempdir);
 
302
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
316
303
    return false;
317
304
  }
318
305
  
319
306
  /* Create new GPGME "context" */
320
307
  rc = gpgme_new(&(mc.ctx));
321
308
  if(rc != GPG_ERR_NO_ERROR){
322
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
323
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
324
 
                 gpgme_strerror(rc));
 
309
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
310
            gpgme_strsource(rc), gpgme_strerror(rc));
325
311
    return false;
326
312
  }
327
313
  
346
332
  ssize_t plaintext_length = 0;
347
333
  
348
334
  if(debug){
349
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
335
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
350
336
  }
351
337
  
352
338
  /* Create new GPGME data buffer from memory cryptotext */
353
339
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
354
340
                               0);
355
341
  if(rc != GPG_ERR_NO_ERROR){
356
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
357
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
342
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
343
            gpgme_strsource(rc), gpgme_strerror(rc));
358
344
    return -1;
359
345
  }
360
346
  
361
347
  /* Create new empty GPGME data buffer for the plaintext */
362
348
  rc = gpgme_data_new(&dh_plain);
363
349
  if(rc != GPG_ERR_NO_ERROR){
364
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
365
 
                 "bad gpgme_data_new: %s: %s\n",
366
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
350
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
351
            gpgme_strsource(rc), gpgme_strerror(rc));
367
352
    gpgme_data_release(dh_crypto);
368
353
    return -1;
369
354
  }
372
357
     data buffer */
373
358
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
374
359
  if(rc != GPG_ERR_NO_ERROR){
375
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
376
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
360
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
361
            gpgme_strsource(rc), gpgme_strerror(rc));
377
362
    plaintext_length = -1;
378
363
    if(debug){
379
364
      gpgme_decrypt_result_t result;
380
365
      result = gpgme_op_decrypt_result(mc.ctx);
381
366
      if(result == NULL){
382
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
367
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
383
368
      } else {
384
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
385
 
                     result->unsupported_algorithm);
386
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
387
 
                     result->wrong_key_usage);
 
369
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
370
                result->unsupported_algorithm);
 
371
        fprintf(stderr, "Wrong key usage: %u\n",
 
372
                result->wrong_key_usage);
388
373
        if(result->file_name != NULL){
389
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
374
          fprintf(stderr, "File name: %s\n", result->file_name);
390
375
        }
391
376
        gpgme_recipient_t recipient;
392
377
        recipient = result->recipients;
393
378
        while(recipient != NULL){
394
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
395
 
                       gpgme_pubkey_algo_name
396
 
                       (recipient->pubkey_algo));
397
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
398
 
          fprintf_plus(stderr, "Secret key available: %s\n",
399
 
                       recipient->status == GPG_ERR_NO_SECKEY
400
 
                       ? "No" : "Yes");
 
379
          fprintf(stderr, "Public key algorithm: %s\n",
 
380
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
381
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
382
          fprintf(stderr, "Secret key available: %s\n",
 
383
                  recipient->status == GPG_ERR_NO_SECKEY
 
384
                  ? "No" : "Yes");
401
385
          recipient = recipient->next;
402
386
        }
403
387
      }
406
390
  }
407
391
  
408
392
  if(debug){
409
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
393
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
410
394
  }
411
395
  
412
396
  /* Seek back to the beginning of the GPGME plaintext data buffer */
419
403
  *plaintext = NULL;
420
404
  while(true){
421
405
    plaintext_capacity = incbuffer(plaintext,
422
 
                                   (size_t)plaintext_length,
423
 
                                   plaintext_capacity);
 
406
                                      (size_t)plaintext_length,
 
407
                                      plaintext_capacity);
424
408
    if(plaintext_capacity == 0){
425
 
      perror_plus("incbuffer");
426
 
      plaintext_length = -1;
427
 
      goto decrypt_end;
 
409
        perror_plus("incbuffer");
 
410
        plaintext_length = -1;
 
411
        goto decrypt_end;
428
412
    }
429
413
    
430
414
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
443
427
  }
444
428
  
445
429
  if(debug){
446
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
430
    fprintf(stderr, "Decrypted password is: ");
447
431
    for(ssize_t i = 0; i < plaintext_length; i++){
448
432
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
449
433
    }
471
455
/* GnuTLS log function callback */
472
456
static void debuggnutls(__attribute__((unused)) int level,
473
457
                        const char* string){
474
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
458
  fprintf(stderr, "GnuTLS: %s", string);
475
459
}
476
460
 
477
461
static int init_gnutls_global(const char *pubkeyfilename,
479
463
  int ret;
480
464
  
481
465
  if(debug){
482
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
466
    fprintf(stderr, "Initializing GnuTLS\n");
483
467
  }
484
468
  
485
469
  ret = gnutls_global_init();
486
470
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
488
 
                 safer_gnutls_strerror(ret));
 
471
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
472
            safer_gnutls_strerror(ret));
489
473
    return -1;
490
474
  }
491
475
  
500
484
  /* OpenPGP credentials */
501
485
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
502
486
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
504
 
                 safer_gnutls_strerror(ret));
 
487
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
488
            safer_gnutls_strerror(ret));
505
489
    gnutls_global_deinit();
506
490
    return -1;
507
491
  }
508
492
  
509
493
  if(debug){
510
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
511
 
                 " secret key %s as GnuTLS credentials\n",
512
 
                 pubkeyfilename,
513
 
                 seckeyfilename);
 
494
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
495
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
496
            seckeyfilename);
514
497
  }
515
498
  
516
499
  ret = gnutls_certificate_set_openpgp_key_file
517
500
    (mc.cred, pubkeyfilename, seckeyfilename,
518
501
     GNUTLS_OPENPGP_FMT_BASE64);
519
502
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf_plus(stderr,
521
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
522
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
523
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
524
 
                 safer_gnutls_strerror(ret));
 
503
    fprintf(stderr,
 
504
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
505
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
506
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
507
            safer_gnutls_strerror(ret));
525
508
    goto globalfail;
526
509
  }
527
510
  
528
511
  /* GnuTLS server initialization */
529
512
  ret = gnutls_dh_params_init(&mc.dh_params);
530
513
  if(ret != GNUTLS_E_SUCCESS){
531
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
532
 
                 " initialization: %s\n",
533
 
                 safer_gnutls_strerror(ret));
 
514
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
515
            " %s\n", safer_gnutls_strerror(ret));
534
516
    goto globalfail;
535
517
  }
536
518
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
537
519
  if(ret != GNUTLS_E_SUCCESS){
538
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
520
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
521
            safer_gnutls_strerror(ret));
540
522
    goto globalfail;
541
523
  }
542
524
  
562
544
    }
563
545
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
564
546
  if(ret != GNUTLS_E_SUCCESS){
565
 
    fprintf_plus(stderr,
566
 
                 "Error in GnuTLS session initialization: %s\n",
567
 
                 safer_gnutls_strerror(ret));
 
547
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
548
            safer_gnutls_strerror(ret));
568
549
  }
569
550
  
570
551
  {
577
558
      }
578
559
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
579
560
    if(ret != GNUTLS_E_SUCCESS){
580
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
581
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
582
 
                   safer_gnutls_strerror(ret));
 
561
      fprintf(stderr, "Syntax error at: %s\n", err);
 
562
      fprintf(stderr, "GnuTLS error: %s\n",
 
563
              safer_gnutls_strerror(ret));
583
564
      gnutls_deinit(*session);
584
565
      return -1;
585
566
    }
594
575
    }
595
576
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
596
577
  if(ret != GNUTLS_E_SUCCESS){
597
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
598
 
                 safer_gnutls_strerror(ret));
 
578
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
579
            safer_gnutls_strerror(ret));
599
580
    gnutls_deinit(*session);
600
581
    return -1;
601
582
  }
646
627
    pf = PF_INET;
647
628
    break;
648
629
  default:
649
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
630
    fprintf(stderr, "Bad address family: %d\n", af);
650
631
    errno = EINVAL;
651
632
    return -1;
652
633
  }
657
638
  }
658
639
  
659
640
  if(debug){
660
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
661
 
                 PRIu16 "\n", ip, port);
 
641
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
642
            "\n", ip, port);
662
643
  }
663
644
  
664
645
  tcp_sd = socket(pf, SOCK_STREAM, 0);
690
671
  }
691
672
  if(ret == 0){
692
673
    int e = errno;
693
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
674
    fprintf(stderr, "Bad address: %s\n", ip);
694
675
    errno = e;
695
676
    goto mandos_end;
696
677
  }
701
682
    
702
683
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
703
684
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
704
 
                                -Wunreachable-code*/
 
685
                              -Wunreachable-code*/
705
686
      if(if_index == AVAHI_IF_UNSPEC){
706
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
707
 
                     " incomplete without a network interface\n");
 
687
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
688
                " without a network interface\n");
708
689
        errno = EINVAL;
709
690
        goto mandos_end;
710
691
      }
728
709
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
729
710
        perror_plus("if_indextoname");
730
711
      } else {
731
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
732
 
                     "\n", ip, interface, port);
 
712
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
713
                ip, interface, port);
733
714
      }
734
715
    } else {
735
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
736
 
                   ip, port);
 
716
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
717
              port);
737
718
    }
738
719
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
739
720
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
749
730
      perror_plus("inet_ntop");
750
731
    } else {
751
732
      if(strcmp(addrstr, ip) != 0){
752
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
733
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
753
734
      }
754
735
    }
755
736
  }
783
764
  while(true){
784
765
    size_t out_size = strlen(out);
785
766
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
786
 
                                        out_size - written));
 
767
                                   out_size - written));
787
768
    if(ret == -1){
788
769
      int e = errno;
789
770
      perror_plus("write");
809
790
  }
810
791
  
811
792
  if(debug){
812
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
793
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
813
794
  }
814
795
  
815
796
  if(quit_now){
835
816
  
836
817
  if(ret != GNUTLS_E_SUCCESS){
837
818
    if(debug){
838
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
819
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
839
820
      gnutls_perror(ret);
840
821
    }
841
822
    errno = EPROTO;
845
826
  /* Read OpenPGP packet that contains the wanted password */
846
827
  
847
828
  if(debug){
848
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
849
 
                 " %s\n", ip);
 
829
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
830
            ip);
850
831
  }
851
832
  
852
833
  while(true){
857
838
    }
858
839
    
859
840
    buffer_capacity = incbuffer(&buffer, buffer_length,
860
 
                                buffer_capacity);
 
841
                                   buffer_capacity);
861
842
    if(buffer_capacity == 0){
862
843
      int e = errno;
863
844
      perror_plus("incbuffer");
890
871
          }
891
872
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
892
873
        if(ret < 0){
893
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
894
 
                       "***\n");
 
874
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
895
875
          gnutls_perror(ret);
896
876
          errno = EPROTO;
897
877
          goto mandos_end;
898
878
        }
899
879
        break;
900
880
      default:
901
 
        fprintf_plus(stderr, "Unknown error while reading data from"
902
 
                     " encrypted session with Mandos server\n");
 
881
        fprintf(stderr, "Unknown error while reading data from"
 
882
                " encrypted session with Mandos server\n");
903
883
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
904
884
        errno = EIO;
905
885
        goto mandos_end;
910
890
  }
911
891
  
912
892
  if(debug){
913
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
893
    fprintf(stderr, "Closing TLS session\n");
914
894
  }
915
895
  
916
896
  if(quit_now){
928
908
  
929
909
  if(buffer_length > 0){
930
910
    ssize_t decrypted_buffer_size;
931
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
911
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
912
                                               buffer_length,
932
913
                                               &decrypted_buffer);
933
914
    if(decrypted_buffer_size >= 0){
934
915
      
945
926
        if(ret == 0 and ferror(stdout)){
946
927
          int e = errno;
947
928
          if(debug){
948
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
949
 
                         strerror(errno));
 
929
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
930
                    strerror(errno));
950
931
          }
951
932
          errno = e;
952
933
          goto mandos_end;
1009
990
  switch(event){
1010
991
  default:
1011
992
  case AVAHI_RESOLVER_FAILURE:
1012
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1013
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1014
 
                 domain,
1015
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
993
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
994
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
995
            avahi_strerror(avahi_server_errno(mc.server)));
1016
996
    break;
1017
997
    
1018
998
  case AVAHI_RESOLVER_FOUND:
1020
1000
      char ip[AVAHI_ADDRESS_STR_MAX];
1021
1001
      avahi_address_snprint(ip, sizeof(ip), address);
1022
1002
      if(debug){
1023
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1024
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1025
 
                     host_name, ip, (intmax_t)interface, port);
 
1003
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1004
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1005
                ip, (intmax_t)interface, port);
1026
1006
      }
1027
1007
      int ret = start_mandos_communication(ip, port, interface,
1028
1008
                                           avahi_proto_to_af(proto));
1060
1040
  default:
1061
1041
  case AVAHI_BROWSER_FAILURE:
1062
1042
    
1063
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1064
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1043
    fprintf(stderr, "(Avahi browser) %s\n",
 
1044
            avahi_strerror(avahi_server_errno(mc.server)));
1065
1045
    avahi_simple_poll_quit(mc.simple_poll);
1066
1046
    return;
1067
1047
    
1074
1054
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1075
1055
                                    name, type, domain, protocol, 0,
1076
1056
                                    resolve_callback, NULL) == NULL)
1077
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1078
 
                   " %s\n", name,
1079
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1057
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1058
              name, avahi_strerror(avahi_server_errno(mc.server)));
1080
1059
    break;
1081
1060
    
1082
1061
  case AVAHI_BROWSER_REMOVE:
1085
1064
  case AVAHI_BROWSER_ALL_FOR_NOW:
1086
1065
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1087
1066
    if(debug){
1088
 
      fprintf_plus(stderr, "No Mandos server found, still"
1089
 
                   " searching...\n");
 
1067
      fprintf(stderr, "No Mandos server found, still searching...\n");
1090
1068
    }
1091
1069
    break;
1092
1070
  }
1107
1085
  errno = old_errno;
1108
1086
}
1109
1087
 
1110
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1111
 
  int ret;
1112
 
  
1113
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1114
 
  if(s < 0){
1115
 
    perror_plus("socket");
1116
 
    return false;
1117
 
  }
1118
 
  strcpy(ifr->ifr_name, ifname);
1119
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1120
 
  if(ret == -1){
 
1088
/* 
 
1089
 * This function determines if a directory entry in /sys/class/net
 
1090
 * corresponds to an acceptable network device.
 
1091
 * (This function is passed to scandir(3) as a filter function.)
 
1092
 */
 
1093
int good_interface(const struct dirent *if_entry){
 
1094
  ssize_t ssret;
 
1095
  char *flagname = NULL;
 
1096
  if(if_entry->d_name[0] == '.'){
 
1097
    return 0;
 
1098
  }
 
1099
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1100
                     if_entry->d_name);
 
1101
  if(ret < 0){
 
1102
    perror_plus("asprintf");
 
1103
    return 0;
 
1104
  }
 
1105
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1106
  if(flags_fd == -1){
 
1107
    perror_plus("open");
 
1108
    free(flagname);
 
1109
    return 0;
 
1110
  }
 
1111
  free(flagname);
 
1112
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1113
  /* read line from flags_fd */
 
1114
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1115
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1116
  flagstring[(size_t)to_read] = '\0';
 
1117
  if(flagstring == NULL){
 
1118
    perror_plus("malloc");
 
1119
    close(flags_fd);
 
1120
    return 0;
 
1121
  }
 
1122
  while(to_read > 0){
 
1123
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1124
                                             (size_t)to_read));
 
1125
    if(ssret == -1){
 
1126
      perror_plus("read");
 
1127
      free(flagstring);
 
1128
      close(flags_fd);
 
1129
      return 0;
 
1130
    }
 
1131
    to_read -= ssret;
 
1132
    if(ssret == 0){
 
1133
      break;
 
1134
    }
 
1135
  }
 
1136
  close(flags_fd);
 
1137
  intmax_t tmpmax;
 
1138
  char *tmp;
 
1139
  errno = 0;
 
1140
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1141
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1142
                                         and not (isspace(*tmp)))
 
1143
     or tmpmax != (ifreq_flags)tmpmax){
1121
1144
    if(debug){
1122
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1145
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1146
              flagstring, if_entry->d_name);
1123
1147
    }
1124
 
    return false;
 
1148
    free(flagstring);
 
1149
    return 0;
1125
1150
  }
1126
 
  return true;
1127
 
}
1128
 
 
1129
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1130
 
  
 
1151
  free(flagstring);
 
1152
  ifreq_flags flags = (ifreq_flags)tmpmax;
1131
1153
  /* Reject the loopback device */
1132
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1154
  if(flags & IFF_LOOPBACK){
1133
1155
    if(debug){
1134
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1135
 
                   ifname);
 
1156
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1157
              if_entry->d_name);
1136
1158
    }
1137
 
    return false;
 
1159
    return 0;
1138
1160
  }
1139
1161
  /* Accept point-to-point devices only if connect_to is specified */
1140
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1162
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1141
1163
    if(debug){
1142
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1143
 
                   " \"%s\"\n", ifname);
 
1164
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1165
              if_entry->d_name);
1144
1166
    }
1145
 
    return true;
 
1167
    return 1;
1146
1168
  }
1147
1169
  /* Otherwise, reject non-broadcast-capable devices */
1148
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1170
  if(not (flags & IFF_BROADCAST)){
1149
1171
    if(debug){
1150
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1151
 
                   " \"%s\"\n", ifname);
 
1172
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1173
              if_entry->d_name);
1152
1174
    }
1153
 
    return false;
 
1175
    return 0;
1154
1176
  }
1155
1177
  /* Reject non-ARP interfaces (including dummy interfaces) */
1156
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1178
  if(flags & IFF_NOARP){
1157
1179
    if(debug){
1158
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1159
 
                   ifname);
 
1180
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1181
              if_entry->d_name);
1160
1182
    }
1161
 
    return false;
 
1183
    return 0;
1162
1184
  }
1163
 
  
1164
1185
  /* Accept this device */
1165
1186
  if(debug){
1166
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1167
 
  }
1168
 
  return true;
1169
 
}
1170
 
 
1171
 
/* 
1172
 
 * This function determines if a directory entry in /sys/class/net
1173
 
 * corresponds to an acceptable network device.
1174
 
 * (This function is passed to scandir(3) as a filter function.)
1175
 
 */
1176
 
int good_interface(const struct dirent *if_entry){
1177
 
  if(if_entry->d_name[0] == '.'){
1178
 
    return 0;
1179
 
  }
1180
 
  
1181
 
  struct ifreq ifr;
1182
 
  if(not get_flags(if_entry->d_name, &ifr)){
1183
 
    if(debug){
1184
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1185
 
                   "\"%s\"\n", if_entry->d_name);
1186
 
    }
1187
 
    return 0;
1188
 
  }
1189
 
  
1190
 
  if(not good_flags(if_entry->d_name, &ifr)){
1191
 
    return 0;
1192
 
  }
1193
 
  return 1;
1194
 
}
1195
 
 
1196
 
/* 
1197
 
 * This function determines if a directory entry in /sys/class/net
1198
 
 * corresponds to an acceptable network device which is up.
1199
 
 * (This function is passed to scandir(3) as a filter function.)
1200
 
 */
1201
 
int up_interface(const struct dirent *if_entry){
1202
 
  if(if_entry->d_name[0] == '.'){
1203
 
    return 0;
1204
 
  }
1205
 
  
1206
 
  struct ifreq ifr;
1207
 
  if(not get_flags(if_entry->d_name, &ifr)){
1208
 
    if(debug){
1209
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1210
 
                   "\"%s\"\n", if_entry->d_name);
1211
 
    }
1212
 
    return 0;
1213
 
  }
1214
 
  
1215
 
  /* Reject down interfaces */
1216
 
  if(not (ifr.ifr_flags & IFF_UP)){
1217
 
    if(debug){
1218
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1219
 
                   if_entry->d_name);
1220
 
    }
1221
 
    return 0;
1222
 
  }
1223
 
  
1224
 
  /* Reject non-running interfaces */
1225
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1226
 
    if(debug){
1227
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1228
 
                   if_entry->d_name);
1229
 
    }
1230
 
    return 0;
1231
 
  }
1232
 
  
1233
 
  if(not good_flags(if_entry->d_name, &ifr)){
1234
 
    return 0;
 
1187
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1188
            if_entry->d_name);
1235
1189
  }
1236
1190
  return 1;
1237
1191
}
1247
1201
  return 1;
1248
1202
}
1249
1203
 
1250
 
/* Is this directory entry a runnable program? */
1251
 
int runnable_hook(const struct dirent *direntry){
1252
 
  int ret;
1253
 
  size_t sret;
1254
 
  struct stat st;
1255
 
  
1256
 
  if((direntry->d_name)[0] == '\0'){
1257
 
    /* Empty name? */
1258
 
    return 0;
1259
 
  }
1260
 
  
1261
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1262
 
                "abcdefghijklmnopqrstuvwxyz"
1263
 
                "0123456789"
1264
 
                "_-");
1265
 
  if((direntry->d_name)[sret] != '\0'){
1266
 
    /* Contains non-allowed characters */
1267
 
    if(debug){
1268
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1269
 
                   direntry->d_name);
1270
 
    }
1271
 
    return 0;
1272
 
  }
1273
 
  
1274
 
  char *fullname = NULL;
1275
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1276
 
  if(ret < 0){
1277
 
    perror_plus("asprintf");
1278
 
    return 0;
1279
 
  }
1280
 
  
1281
 
  ret = stat(fullname, &st);
1282
 
  if(ret == -1){
1283
 
    if(debug){
1284
 
      perror_plus("Could not stat hook");
1285
 
    }
1286
 
    return 0;
1287
 
  }
1288
 
  if(not (S_ISREG(st.st_mode))){
1289
 
    /* Not a regular file */
1290
 
    if(debug){
1291
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1292
 
                   direntry->d_name);
1293
 
    }
1294
 
    return 0;
1295
 
  }
1296
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1297
 
    /* Not executable */
1298
 
    if(debug){
1299
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1300
 
                   direntry->d_name);
1301
 
    }
1302
 
    return 0;
1303
 
  }
1304
 
  if(debug){
1305
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1306
 
                 direntry->d_name);
1307
 
  }
1308
 
  return 1;
1309
 
}
1310
 
 
1311
1204
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1312
1205
  int ret;
1313
1206
  struct timespec now;
1317
1210
  while(true){
1318
1211
    if(mc.current_server == NULL){
1319
1212
      if (debug){
1320
 
        fprintf_plus(stderr, "Wait until first server is found."
1321
 
                     " No timeout!\n");
 
1213
        fprintf(stderr,
 
1214
                "Wait until first server is found. No timeout!\n");
1322
1215
      }
1323
1216
      ret = avahi_simple_poll_iterate(s, -1);
1324
1217
    } else {
1325
1218
      if (debug){
1326
 
        fprintf_plus(stderr, "Check current_server if we should run"
1327
 
                     " it, or wait\n");
 
1219
        fprintf(stderr, "Check current_server if we should run it,"
 
1220
                " or wait\n");
1328
1221
      }
1329
1222
      /* the current time */
1330
1223
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1346
1239
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1347
1240
      
1348
1241
      if (debug){
1349
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1350
 
                     block_time);
 
1242
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1351
1243
      }
1352
1244
      
1353
1245
      if(block_time <= 0){
1373
1265
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1374
1266
    }
1375
1267
    if(ret != 0){
1376
 
      if (ret > 0 or errno != EINTR){
 
1268
      if (ret > 0 or errno != EINTR) {
1377
1269
        return (ret != 1) ? ret : 0;
1378
1270
      }
1379
1271
    }
1380
1272
  }
1381
1273
}
1382
1274
 
1383
 
bool run_network_hooks(const char *mode, const char *interface,
1384
 
                       const float delay){
1385
 
  struct dirent **direntries;
1386
 
  struct dirent *direntry;
1387
 
  int ret;
1388
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1389
 
                         alphasort);
1390
 
  if(numhooks == -1){
1391
 
    perror_plus("scandir");
1392
 
  } else {
1393
 
    int devnull = open("/dev/null", O_RDONLY);
1394
 
    for(int i = 0; i < numhooks; i++){
1395
 
      direntry = direntries[i];
1396
 
      char *fullname = NULL;
1397
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1398
 
      if(ret < 0){
1399
 
        perror_plus("asprintf");
1400
 
        continue;
1401
 
      }
1402
 
      if(debug){
1403
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1404
 
                     direntry->d_name);
1405
 
      }
1406
 
      pid_t hook_pid = fork();
1407
 
      if(hook_pid == 0){
1408
 
        /* Child */
1409
 
        dup2(devnull, STDIN_FILENO);
1410
 
        close(devnull);
1411
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1412
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1413
 
        if(ret == -1){
1414
 
          perror_plus("setenv");
1415
 
          _exit(EX_OSERR);
1416
 
        }
1417
 
        ret = setenv("DEVICE", interface, 1);
1418
 
        if(ret == -1){
1419
 
          perror_plus("setenv");
1420
 
          _exit(EX_OSERR);
1421
 
        }
1422
 
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1423
 
        if(ret == -1){
1424
 
          perror_plus("setenv");
1425
 
          _exit(EX_OSERR);
1426
 
        }
1427
 
        ret = setenv("MODE", mode, 1);
1428
 
        if(ret == -1){
1429
 
          perror_plus("setenv");
1430
 
          _exit(EX_OSERR);
1431
 
        }
1432
 
        char *delaystring;
1433
 
        ret = asprintf(&delaystring, "%f", delay);
1434
 
        if(ret == -1){
1435
 
          perror_plus("asprintf");
1436
 
          _exit(EX_OSERR);
1437
 
        }
1438
 
        ret = setenv("DELAY", delaystring, 1);
1439
 
        if(ret == -1){
1440
 
          free(delaystring);
1441
 
          perror_plus("setenv");
1442
 
          _exit(EX_OSERR);
1443
 
        }
1444
 
        free(delaystring);
1445
 
        ret = execl(fullname, direntry->d_name, mode, NULL);
1446
 
        perror_plus("execl");
1447
 
      } else {
1448
 
        int status;
1449
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1450
 
          perror_plus("waitpid");
1451
 
          free(fullname);
1452
 
          continue;
1453
 
        }
1454
 
        if(WIFEXITED(status)){
1455
 
          if(WEXITSTATUS(status) != 0){
1456
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1457
 
                         " with status %d\n", direntry->d_name,
1458
 
                         WEXITSTATUS(status));
1459
 
            free(fullname);
1460
 
            continue;
1461
 
          }
1462
 
        } else if(WIFSIGNALED(status)){
1463
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1464
 
                       " signal %d\n", direntry->d_name,
1465
 
                       WTERMSIG(status));
1466
 
          free(fullname);
1467
 
          continue;
1468
 
        } else {
1469
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1470
 
                       " crashed\n", direntry->d_name);
1471
 
          free(fullname);
1472
 
          continue;
1473
 
        }
1474
 
      }
1475
 
      free(fullname);
1476
 
      if(debug){
1477
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1478
 
                     direntry->d_name);
1479
 
      }
1480
 
    }
1481
 
    close(devnull);
1482
 
  }
1483
 
  return true;
1484
 
}
1485
 
 
1486
1275
int main(int argc, char *argv[]){
1487
1276
  AvahiSServiceBrowser *sb = NULL;
1488
1277
  int error;
1570
1359
        .arg = "SECONDS",
1571
1360
        .doc = "Retry interval used when denied by the mandos server",
1572
1361
        .group = 2 },
1573
 
      { .name = "network-hook-dir", .key = 133,
1574
 
        .arg = "DIR",
1575
 
        .doc = "Directory where network hooks are located",
1576
 
        .group = 2 },
1577
1362
      /*
1578
1363
       * These reproduce what we would get without ARGP_NO_HELP
1579
1364
       */
1632
1417
          argp_error(state, "Bad retry interval");
1633
1418
        }
1634
1419
        break;
1635
 
      case 133:                 /* --network-hook-dir */
1636
 
        hookdir = arg;
1637
 
        break;
1638
1420
        /*
1639
1421
         * These reproduce what we would get without ARGP_NO_HELP
1640
1422
         */
1646
1428
        argp_state_help(state, state->out_stream,
1647
1429
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1648
1430
      case 'V':                 /* --version */
1649
 
        fprintf_plus(state->out_stream,
1650
 
                     "Mandos plugin mandos-client: ");
1651
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1431
        fprintf(state->out_stream, "%s\n", argp_program_version);
1652
1432
        exit(argp_err_exit_status);
1653
1433
        break;
1654
1434
      default:
1678
1458
    }
1679
1459
  }
1680
1460
    
1681
 
  if(getuid() == 0){
 
1461
  {
1682
1462
    /* Work around Debian bug #633582:
1683
1463
       <http://bugs.debian.org/633582> */
1684
1464
    struct stat st;
1699
1479
        if(ret == -1){
1700
1480
          perror_plus("fstat");
1701
1481
        } else {
1702
 
          if(S_ISREG(st.st_mode)
1703
 
             and st.st_uid == 0 and st.st_gid == 0){
 
1482
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1704
1483
            ret = fchown(seckey_fd, uid, gid);
1705
1484
            if(ret == -1){
1706
1485
              perror_plus("fchown");
1720
1499
        if(ret == -1){
1721
1500
          perror_plus("fstat");
1722
1501
        } else {
1723
 
          if(S_ISREG(st.st_mode)
1724
 
             and st.st_uid == 0 and st.st_gid == 0){
 
1502
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1725
1503
            ret = fchown(pubkey_fd, uid, gid);
1726
1504
            if(ret == -1){
1727
1505
              perror_plus("fchown");
1740
1518
    }
1741
1519
  }
1742
1520
  
1743
 
  /* Run network hooks */
1744
 
  {
1745
 
    if(getuid() == 0){
1746
 
      /* Re-raise priviliges */
1747
 
      errno = 0;
1748
 
      ret = seteuid(0);
1749
 
      if(ret == -1){
1750
 
        perror_plus("seteuid");
1751
 
      }
1752
 
    }
1753
 
    if(not run_network_hooks("start", interface, delay)){
1754
 
      goto end;
1755
 
    }
1756
 
    if(getuid() == 0){
1757
 
      /* Lower privileges */
1758
 
      errno = 0;
1759
 
      ret = seteuid(uid);
1760
 
      if(ret == -1){
1761
 
        perror_plus("seteuid");
1762
 
      }
1763
 
    }
1764
 
  }
1765
 
  
1766
1521
  if(not debug){
1767
1522
    avahi_set_log_function(empty_log);
1768
1523
  }
1769
 
  
 
1524
 
1770
1525
  if(interface[0] == '\0'){
1771
1526
    struct dirent **direntries;
1772
 
    /* First look for interfaces that are up */
1773
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1527
    ret = scandir(sys_class_net, &direntries, good_interface,
1774
1528
                  alphasort);
1775
 
    if(ret == 0){
1776
 
      /* No up interfaces, look for any good interfaces */
1777
 
      free(direntries);
1778
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1779
 
                    alphasort);
1780
 
    }
1781
1529
    if(ret >= 1){
1782
 
      /* Pick the first interface returned */
 
1530
      /* Pick the first good interface */
1783
1531
      interface = strdup(direntries[0]->d_name);
1784
1532
      if(debug){
1785
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1533
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1786
1534
      }
1787
1535
      if(interface == NULL){
1788
1536
        perror_plus("malloc");
1793
1541
      free(direntries);
1794
1542
    } else {
1795
1543
      free(direntries);
1796
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1544
      fprintf(stderr, "Could not find a network interface\n");
1797
1545
      exitcode = EXIT_FAILURE;
1798
1546
      goto end;
1799
1547
    }
1805
1553
  srand((unsigned int) time(NULL));
1806
1554
  mc.simple_poll = avahi_simple_poll_new();
1807
1555
  if(mc.simple_poll == NULL){
1808
 
    fprintf_plus(stderr,
1809
 
                 "Avahi: Failed to create simple poll object.\n");
 
1556
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1810
1557
    exitcode = EX_UNAVAILABLE;
1811
1558
    goto end;
1812
1559
  }
1878
1625
  if(strcmp(interface, "none") != 0){
1879
1626
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1880
1627
    if(if_index == 0){
1881
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1628
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1882
1629
      exitcode = EX_UNAVAILABLE;
1883
1630
      goto end;
1884
1631
    }
2004
1751
#endif  /* __linux__ */
2005
1752
    /* Lower privileges */
2006
1753
    errno = 0;
2007
 
    /* Lower privileges */
2008
 
    ret = seteuid(uid);
2009
 
    if(ret == -1){
2010
 
      perror_plus("seteuid");
 
1754
    if(take_down_interface){
 
1755
      /* Lower privileges */
 
1756
      ret = seteuid(uid);
 
1757
      if(ret == -1){
 
1758
        perror_plus("seteuid");
 
1759
      }
 
1760
    } else {
 
1761
      /* Lower privileges permanently */
 
1762
      ret = setuid(uid);
 
1763
      if(ret == -1){
 
1764
        perror_plus("setuid");
 
1765
      }
2011
1766
    }
2012
1767
  }
2013
1768
  
2017
1772
  
2018
1773
  ret = init_gnutls_global(pubkey, seckey);
2019
1774
  if(ret == -1){
2020
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1775
    fprintf(stderr, "init_gnutls_global failed\n");
2021
1776
    exitcode = EX_UNAVAILABLE;
2022
1777
    goto end;
2023
1778
  } else {
2039
1794
  }
2040
1795
  
2041
1796
  if(not init_gpgme(pubkey, seckey, tempdir)){
2042
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1797
    fprintf(stderr, "init_gpgme failed\n");
2043
1798
    exitcode = EX_UNAVAILABLE;
2044
1799
    goto end;
2045
1800
  } else {
2055
1810
    /* (Mainly meant for debugging) */
2056
1811
    char *address = strrchr(connect_to, ':');
2057
1812
    if(address == NULL){
2058
 
      fprintf_plus(stderr, "No colon in address\n");
 
1813
      fprintf(stderr, "No colon in address\n");
2059
1814
      exitcode = EX_USAGE;
2060
1815
      goto end;
2061
1816
    }
2069
1824
    tmpmax = strtoimax(address+1, &tmp, 10);
2070
1825
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2071
1826
       or tmpmax != (uint16_t)tmpmax){
2072
 
      fprintf_plus(stderr, "Bad port number\n");
 
1827
      fprintf(stderr, "Bad port number\n");
2073
1828
      exitcode = EX_USAGE;
2074
1829
      goto end;
2075
1830
    }
2105
1860
        break;
2106
1861
      }
2107
1862
      if(debug){
2108
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2109
 
                     (int)retry_interval);
 
1863
        fprintf(stderr, "Retrying in %d seconds\n",
 
1864
                (int)retry_interval);
2110
1865
      }
2111
1866
      sleep((int)retry_interval);
2112
1867
    }
2114
1869
    if (not quit_now){
2115
1870
      exitcode = EXIT_SUCCESS;
2116
1871
    }
2117
 
    
 
1872
 
2118
1873
    goto end;
2119
1874
  }
2120
1875
  
2142
1897
  
2143
1898
  /* Check if creating the Avahi server object succeeded */
2144
1899
  if(mc.server == NULL){
2145
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2146
 
                 avahi_strerror(error));
 
1900
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1901
            avahi_strerror(error));
2147
1902
    exitcode = EX_UNAVAILABLE;
2148
1903
    goto end;
2149
1904
  }
2157
1912
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2158
1913
                                   NULL, 0, browse_callback, NULL);
2159
1914
  if(sb == NULL){
2160
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2161
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1915
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1916
            avahi_strerror(avahi_server_errno(mc.server)));
2162
1917
    exitcode = EX_UNAVAILABLE;
2163
1918
    goto end;
2164
1919
  }
2170
1925
  /* Run the main loop */
2171
1926
  
2172
1927
  if(debug){
2173
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
1928
    fprintf(stderr, "Starting Avahi loop search\n");
2174
1929
  }
2175
1930
 
2176
1931
  ret = avahi_loop_with_timeout(mc.simple_poll,
2177
1932
                                (int)(retry_interval * 1000));
2178
1933
  if(debug){
2179
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2180
 
                 (ret == 0) ? "successfully" : "with error");
 
1934
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1935
            (ret == 0) ? "successfully" : "with error");
2181
1936
  }
2182
1937
  
2183
1938
 end:
2184
1939
  
2185
1940
  if(debug){
2186
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1941
    fprintf(stderr, "%s exiting\n", argv[0]);
2187
1942
  }
2188
1943
  
2189
1944
  /* Cleanup things */
2205
1960
  if(gpgme_initialized){
2206
1961
    gpgme_release(mc.ctx);
2207
1962
  }
2208
 
  
 
1963
 
2209
1964
  /* Cleans up the circular linked list of Mandos servers the client
2210
1965
     has seen */
2211
1966
  if(mc.current_server != NULL){
2217
1972
    }
2218
1973
  }
2219
1974
  
2220
 
  /* Re-raise priviliges */
2221
 
  {
2222
 
    if(getuid() == 0){
2223
 
      errno = 0;
2224
 
      ret = seteuid(0);
2225
 
      if(ret == -1){
2226
 
        perror_plus("seteuid");
2227
 
      }
 
1975
  /* Take down the network interface */
 
1976
  if(take_down_interface){
 
1977
    /* Re-raise priviliges */
 
1978
    errno = 0;
 
1979
    ret = seteuid(0);
 
1980
    if(ret == -1){
 
1981
      perror_plus("seteuid");
2228
1982
    }
2229
 
    
2230
 
    /* Run network hooks */
2231
 
    run_network_hooks("stop", interface, delay);
2232
 
    
2233
 
    /* Take down the network interface */
2234
 
    if(take_down_interface and geteuid() == 0){
 
1983
    if(geteuid() == 0){
2235
1984
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2236
1985
      if(ret == -1){
2237
1986
        perror_plus("ioctl SIOCGIFFLAGS");
2238
 
      } else if(network.ifr_flags & IFF_UP){
 
1987
      } else if(network.ifr_flags & IFF_UP) {
2239
1988
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2240
1989
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2241
1990
        if(ret == -1){
2246
1995
      if(ret == -1){
2247
1996
        perror_plus("close");
2248
1997
      }
2249
 
    }
2250
 
  }
2251
 
  if(getuid() == 0){
2252
 
    /* Lower privileges permanently */
2253
 
    errno = 0;
2254
 
    ret = setuid(uid);
2255
 
    if(ret == -1){
2256
 
      perror_plus("setuid");
 
1998
      /* Lower privileges permanently */
 
1999
      errno = 0;
 
2000
      ret = setuid(uid);
 
2001
      if(ret == -1){
 
2002
        perror_plus("setuid");
 
2003
      }
2257
2004
    }
2258
2005
  }
2259
2006
  
2275
2022
        }
2276
2023
        ret = remove(fullname);
2277
2024
        if(ret == -1){
2278
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2279
 
                       strerror(errno));
 
2025
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2026
                  strerror(errno));
2280
2027
        }
2281
2028
        free(fullname);
2282
2029
      }