/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: teddy at bsnet
  • Date: 2011-12-23 20:00:52 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111223200052-nehnjfy0fogvm4ii
* mandos (initlogger): Take new "debug" argument; all callers changed.
                       Only add console logger in debug mode.
  (main/cleanup): Remove temp file on failure.

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() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
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() */
 
76
                                   setgid(), pause(), _exit() */
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
#include <grp.h>                /* setgroups() */
88
91
 
89
92
#ifdef __linux__
90
93
#include <sys/klog.h>           /* klogctl() */
108
111
                                   init_gnutls_session(),
109
112
                                   GNUTLS_* */
110
113
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
114
                         /* gnutls_certificate_set_openpgp_key_file(),
 
115
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
116
 
114
117
/* GPGME */
115
118
#include <gpgme.h>              /* All GPGME types, constants and
123
126
#define PATHDIR "/conf/conf.d/mandos"
124
127
#define SECKEY "seckey.txt"
125
128
#define PUBKEY "pubkey.txt"
 
129
#define HOOKDIR "/lib/mandos/network-hooks.d"
126
130
 
127
131
bool debug = false;
128
132
static const char mandos_protocol_version[] = "1";
130
134
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
135
static const char sys_class_net[] = "/sys/class/net";
132
136
char *connect_to = NULL;
 
137
const char *hookdir = HOOKDIR;
133
138
 
134
139
/* Doubly linked list that need to be circularly linked when used */
135
140
typedef struct server{
170
175
  perror(print_text);
171
176
}
172
177
 
 
178
int fprintf_plus(FILE *stream, const char *format, ...){
 
179
  va_list ap;
 
180
  va_start (ap, format);
 
181
  
 
182
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
183
                             program_invocation_short_name));
 
184
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
185
}
 
186
 
173
187
/*
174
188
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
189
 * bytes. "buffer_capacity" is how much is currently allocated,
176
190
 * "buffer_length" is how much is already used.
177
191
 */
178
192
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
193
                 size_t buffer_capacity){
180
194
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
195
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
196
    if(buffer == NULL){
188
202
}
189
203
 
190
204
/* Add server to set of servers to retry periodically */
191
 
int add_server(const char *ip, uint16_t port,
192
 
                 AvahiIfIndex if_index,
193
 
                 int af){
 
205
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
206
               int af){
194
207
  int ret;
195
208
  server *new_server = malloc(sizeof(server));
196
209
  if(new_server == NULL){
198
211
    return -1;
199
212
  }
200
213
  *new_server = (server){ .ip = strdup(ip),
201
 
                         .port = port,
202
 
                         .if_index = if_index,
203
 
                         .af = af };
 
214
                          .port = port,
 
215
                          .if_index = if_index,
 
216
                          .af = af };
204
217
  if(new_server->ip == NULL){
205
218
    perror_plus("strdup");
206
219
    return -1;
228
241
/* 
229
242
 * Initialize GPGME.
230
243
 */
231
 
static bool init_gpgme(const char *seckey,
232
 
                       const char *pubkey, const char *tempdir){
 
244
static bool init_gpgme(const char *seckey, const char *pubkey,
 
245
                       const char *tempdir){
233
246
  gpgme_error_t rc;
234
247
  gpgme_engine_info_t engine_info;
235
248
  
250
263
    
251
264
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
252
265
    if(rc != GPG_ERR_NO_ERROR){
253
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
254
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
266
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
267
                   gpgme_strsource(rc), gpgme_strerror(rc));
255
268
      return false;
256
269
    }
257
270
    
258
271
    rc = gpgme_op_import(mc.ctx, pgp_data);
259
272
    if(rc != GPG_ERR_NO_ERROR){
260
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
261
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
273
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
274
                   gpgme_strsource(rc), gpgme_strerror(rc));
262
275
      return false;
263
276
    }
264
277
    
271
284
  }
272
285
  
273
286
  if(debug){
274
 
    fprintf(stderr, "Initializing GPGME\n");
 
287
    fprintf_plus(stderr, "Initializing GPGME\n");
275
288
  }
276
289
  
277
290
  /* Init GPGME */
278
291
  gpgme_check_version(NULL);
279
292
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
280
293
  if(rc != GPG_ERR_NO_ERROR){
281
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
282
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
294
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
295
                 gpgme_strsource(rc), gpgme_strerror(rc));
283
296
    return false;
284
297
  }
285
298
  
286
299
  /* Set GPGME home directory for the OpenPGP engine only */
287
300
  rc = gpgme_get_engine_info(&engine_info);
288
301
  if(rc != GPG_ERR_NO_ERROR){
289
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
290
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
302
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
303
                 gpgme_strsource(rc), gpgme_strerror(rc));
291
304
    return false;
292
305
  }
293
306
  while(engine_info != NULL){
299
312
    engine_info = engine_info->next;
300
313
  }
301
314
  if(engine_info == NULL){
302
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
315
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
316
                 tempdir);
303
317
    return false;
304
318
  }
305
319
  
306
320
  /* Create new GPGME "context" */
307
321
  rc = gpgme_new(&(mc.ctx));
308
322
  if(rc != GPG_ERR_NO_ERROR){
309
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
310
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
323
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
324
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
325
                 gpgme_strerror(rc));
311
326
    return false;
312
327
  }
313
328
  
332
347
  ssize_t plaintext_length = 0;
333
348
  
334
349
  if(debug){
335
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
350
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
336
351
  }
337
352
  
338
353
  /* Create new GPGME data buffer from memory cryptotext */
339
354
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
340
355
                               0);
341
356
  if(rc != GPG_ERR_NO_ERROR){
342
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
343
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
357
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
358
                 gpgme_strsource(rc), gpgme_strerror(rc));
344
359
    return -1;
345
360
  }
346
361
  
347
362
  /* Create new empty GPGME data buffer for the plaintext */
348
363
  rc = gpgme_data_new(&dh_plain);
349
364
  if(rc != GPG_ERR_NO_ERROR){
350
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
351
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
365
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
366
                 "bad gpgme_data_new: %s: %s\n",
 
367
                 gpgme_strsource(rc), gpgme_strerror(rc));
352
368
    gpgme_data_release(dh_crypto);
353
369
    return -1;
354
370
  }
357
373
     data buffer */
358
374
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
359
375
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
361
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
376
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
377
                 gpgme_strsource(rc), gpgme_strerror(rc));
362
378
    plaintext_length = -1;
363
379
    if(debug){
364
380
      gpgme_decrypt_result_t result;
365
381
      result = gpgme_op_decrypt_result(mc.ctx);
366
382
      if(result == NULL){
367
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
383
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
368
384
      } else {
369
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
370
 
                result->unsupported_algorithm);
371
 
        fprintf(stderr, "Wrong key usage: %u\n",
372
 
                result->wrong_key_usage);
 
385
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
386
                     result->unsupported_algorithm);
 
387
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
388
                     result->wrong_key_usage);
373
389
        if(result->file_name != NULL){
374
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
390
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
375
391
        }
376
392
        gpgme_recipient_t recipient;
377
393
        recipient = result->recipients;
378
394
        while(recipient != NULL){
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");
 
395
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
396
                       gpgme_pubkey_algo_name
 
397
                       (recipient->pubkey_algo));
 
398
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
399
          fprintf_plus(stderr, "Secret key available: %s\n",
 
400
                       recipient->status == GPG_ERR_NO_SECKEY
 
401
                       ? "No" : "Yes");
385
402
          recipient = recipient->next;
386
403
        }
387
404
      }
390
407
  }
391
408
  
392
409
  if(debug){
393
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
410
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
394
411
  }
395
412
  
396
413
  /* Seek back to the beginning of the GPGME plaintext data buffer */
403
420
  *plaintext = NULL;
404
421
  while(true){
405
422
    plaintext_capacity = incbuffer(plaintext,
406
 
                                      (size_t)plaintext_length,
407
 
                                      plaintext_capacity);
 
423
                                   (size_t)plaintext_length,
 
424
                                   plaintext_capacity);
408
425
    if(plaintext_capacity == 0){
409
 
        perror_plus("incbuffer");
410
 
        plaintext_length = -1;
411
 
        goto decrypt_end;
 
426
      perror_plus("incbuffer");
 
427
      plaintext_length = -1;
 
428
      goto decrypt_end;
412
429
    }
413
430
    
414
431
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
427
444
  }
428
445
  
429
446
  if(debug){
430
 
    fprintf(stderr, "Decrypted password is: ");
 
447
    fprintf_plus(stderr, "Decrypted password is: ");
431
448
    for(ssize_t i = 0; i < plaintext_length; i++){
432
449
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
433
450
    }
455
472
/* GnuTLS log function callback */
456
473
static void debuggnutls(__attribute__((unused)) int level,
457
474
                        const char* string){
458
 
  fprintf(stderr, "GnuTLS: %s", string);
 
475
  fprintf_plus(stderr, "GnuTLS: %s", string);
459
476
}
460
477
 
461
478
static int init_gnutls_global(const char *pubkeyfilename,
463
480
  int ret;
464
481
  
465
482
  if(debug){
466
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
483
    fprintf_plus(stderr, "Initializing GnuTLS\n");
467
484
  }
468
485
  
469
486
  ret = gnutls_global_init();
470
487
  if(ret != GNUTLS_E_SUCCESS){
471
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
472
 
            safer_gnutls_strerror(ret));
 
488
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
489
                 safer_gnutls_strerror(ret));
473
490
    return -1;
474
491
  }
475
492
  
484
501
  /* OpenPGP credentials */
485
502
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
486
503
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
488
 
            safer_gnutls_strerror(ret));
 
504
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
505
                 safer_gnutls_strerror(ret));
489
506
    gnutls_global_deinit();
490
507
    return -1;
491
508
  }
492
509
  
493
510
  if(debug){
494
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
495
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
496
 
            seckeyfilename);
 
511
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
512
                 " secret key %s as GnuTLS credentials\n",
 
513
                 pubkeyfilename,
 
514
                 seckeyfilename);
497
515
  }
498
516
  
499
517
  ret = gnutls_certificate_set_openpgp_key_file
500
518
    (mc.cred, pubkeyfilename, seckeyfilename,
501
519
     GNUTLS_OPENPGP_FMT_BASE64);
502
520
  if(ret != GNUTLS_E_SUCCESS){
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));
 
521
    fprintf_plus(stderr,
 
522
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
523
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
524
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
525
                 safer_gnutls_strerror(ret));
508
526
    goto globalfail;
509
527
  }
510
528
  
511
529
  /* GnuTLS server initialization */
512
530
  ret = gnutls_dh_params_init(&mc.dh_params);
513
531
  if(ret != GNUTLS_E_SUCCESS){
514
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
515
 
            " %s\n", safer_gnutls_strerror(ret));
 
532
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
533
                 " initialization: %s\n",
 
534
                 safer_gnutls_strerror(ret));
516
535
    goto globalfail;
517
536
  }
518
537
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
519
538
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
521
 
            safer_gnutls_strerror(ret));
 
539
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
540
                 safer_gnutls_strerror(ret));
522
541
    goto globalfail;
523
542
  }
524
543
  
544
563
    }
545
564
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
546
565
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
548
 
            safer_gnutls_strerror(ret));
 
566
    fprintf_plus(stderr,
 
567
                 "Error in GnuTLS session initialization: %s\n",
 
568
                 safer_gnutls_strerror(ret));
549
569
  }
550
570
  
551
571
  {
558
578
      }
559
579
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
560
580
    if(ret != GNUTLS_E_SUCCESS){
561
 
      fprintf(stderr, "Syntax error at: %s\n", err);
562
 
      fprintf(stderr, "GnuTLS error: %s\n",
563
 
              safer_gnutls_strerror(ret));
 
581
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
582
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
583
                   safer_gnutls_strerror(ret));
564
584
      gnutls_deinit(*session);
565
585
      return -1;
566
586
    }
575
595
    }
576
596
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
577
597
  if(ret != GNUTLS_E_SUCCESS){
578
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
579
 
            safer_gnutls_strerror(ret));
 
598
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
599
                 safer_gnutls_strerror(ret));
580
600
    gnutls_deinit(*session);
581
601
    return -1;
582
602
  }
627
647
    pf = PF_INET;
628
648
    break;
629
649
  default:
630
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
650
    fprintf_plus(stderr, "Bad address family: %d\n", af);
631
651
    errno = EINVAL;
632
652
    return -1;
633
653
  }
638
658
  }
639
659
  
640
660
  if(debug){
641
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
642
 
            "\n", ip, port);
 
661
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
662
                 PRIu16 "\n", ip, port);
643
663
  }
644
664
  
645
665
  tcp_sd = socket(pf, SOCK_STREAM, 0);
671
691
  }
672
692
  if(ret == 0){
673
693
    int e = errno;
674
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
694
    fprintf_plus(stderr, "Bad address: %s\n", ip);
675
695
    errno = e;
676
696
    goto mandos_end;
677
697
  }
682
702
    
683
703
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
684
704
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
685
 
                              -Wunreachable-code*/
 
705
                                -Wunreachable-code*/
686
706
      if(if_index == AVAHI_IF_UNSPEC){
687
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
688
 
                " without a network interface\n");
 
707
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
708
                     " incomplete without a network interface\n");
689
709
        errno = EINVAL;
690
710
        goto mandos_end;
691
711
      }
709
729
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
730
        perror_plus("if_indextoname");
711
731
      } else {
712
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
713
 
                ip, interface, port);
 
732
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
733
                     "\n", ip, interface, port);
714
734
      }
715
735
    } else {
716
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
717
 
              port);
 
736
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
737
                   ip, port);
718
738
    }
719
739
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
720
740
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
730
750
      perror_plus("inet_ntop");
731
751
    } else {
732
752
      if(strcmp(addrstr, ip) != 0){
733
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
753
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
734
754
      }
735
755
    }
736
756
  }
764
784
  while(true){
765
785
    size_t out_size = strlen(out);
766
786
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
767
 
                                   out_size - written));
 
787
                                        out_size - written));
768
788
    if(ret == -1){
769
789
      int e = errno;
770
790
      perror_plus("write");
790
810
  }
791
811
  
792
812
  if(debug){
793
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
813
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
794
814
  }
795
815
  
796
816
  if(quit_now){
816
836
  
817
837
  if(ret != GNUTLS_E_SUCCESS){
818
838
    if(debug){
819
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
839
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
820
840
      gnutls_perror(ret);
821
841
    }
822
842
    errno = EPROTO;
826
846
  /* Read OpenPGP packet that contains the wanted password */
827
847
  
828
848
  if(debug){
829
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
830
 
            ip);
 
849
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
850
                 " %s\n", ip);
831
851
  }
832
852
  
833
853
  while(true){
838
858
    }
839
859
    
840
860
    buffer_capacity = incbuffer(&buffer, buffer_length,
841
 
                                   buffer_capacity);
 
861
                                buffer_capacity);
842
862
    if(buffer_capacity == 0){
843
863
      int e = errno;
844
864
      perror_plus("incbuffer");
871
891
          }
872
892
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
873
893
        if(ret < 0){
874
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
894
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
895
                       "***\n");
875
896
          gnutls_perror(ret);
876
897
          errno = EPROTO;
877
898
          goto mandos_end;
878
899
        }
879
900
        break;
880
901
      default:
881
 
        fprintf(stderr, "Unknown error while reading data from"
882
 
                " encrypted session with Mandos server\n");
 
902
        fprintf_plus(stderr, "Unknown error while reading data from"
 
903
                     " encrypted session with Mandos server\n");
883
904
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
884
905
        errno = EIO;
885
906
        goto mandos_end;
890
911
  }
891
912
  
892
913
  if(debug){
893
 
    fprintf(stderr, "Closing TLS session\n");
 
914
    fprintf_plus(stderr, "Closing TLS session\n");
894
915
  }
895
916
  
896
917
  if(quit_now){
908
929
  
909
930
  if(buffer_length > 0){
910
931
    ssize_t decrypted_buffer_size;
911
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
912
 
                                               buffer_length,
 
932
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
913
933
                                               &decrypted_buffer);
914
934
    if(decrypted_buffer_size >= 0){
915
935
      
926
946
        if(ret == 0 and ferror(stdout)){
927
947
          int e = errno;
928
948
          if(debug){
929
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
930
 
                    strerror(errno));
 
949
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
950
                         strerror(errno));
931
951
          }
932
952
          errno = e;
933
953
          goto mandos_end;
990
1010
  switch(event){
991
1011
  default:
992
1012
  case AVAHI_RESOLVER_FAILURE:
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)));
 
1013
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1014
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1015
                 domain,
 
1016
                 avahi_strerror(avahi_server_errno(mc.server)));
996
1017
    break;
997
1018
    
998
1019
  case AVAHI_RESOLVER_FOUND:
1000
1021
      char ip[AVAHI_ADDRESS_STR_MAX];
1001
1022
      avahi_address_snprint(ip, sizeof(ip), address);
1002
1023
      if(debug){
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);
 
1024
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1025
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1026
                     host_name, ip, (intmax_t)interface, port);
1006
1027
      }
1007
1028
      int ret = start_mandos_communication(ip, port, interface,
1008
1029
                                           avahi_proto_to_af(proto));
1040
1061
  default:
1041
1062
  case AVAHI_BROWSER_FAILURE:
1042
1063
    
1043
 
    fprintf(stderr, "(Avahi browser) %s\n",
1044
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1064
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1065
                 avahi_strerror(avahi_server_errno(mc.server)));
1045
1066
    avahi_simple_poll_quit(mc.simple_poll);
1046
1067
    return;
1047
1068
    
1054
1075
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1055
1076
                                    name, type, domain, protocol, 0,
1056
1077
                                    resolve_callback, NULL) == NULL)
1057
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1058
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1078
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1079
                   " %s\n", name,
 
1080
                   avahi_strerror(avahi_server_errno(mc.server)));
1059
1081
    break;
1060
1082
    
1061
1083
  case AVAHI_BROWSER_REMOVE:
1064
1086
  case AVAHI_BROWSER_ALL_FOR_NOW:
1065
1087
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1066
1088
    if(debug){
1067
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1089
      fprintf_plus(stderr, "No Mandos server found, still"
 
1090
                   " searching...\n");
1068
1091
    }
1069
1092
    break;
1070
1093
  }
1085
1108
  errno = old_errno;
1086
1109
}
1087
1110
 
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;
 
1111
bool get_flags(const char *ifname, struct ifreq *ifr){
1095
1112
  int ret;
1096
 
  if(if_entry->d_name[0] == '.'){
1097
 
    return 0;
1098
 
  }
 
1113
  
1099
1114
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1100
1115
  if(s < 0){
1101
1116
    perror_plus("socket");
1102
 
    return 0;
 
1117
    return false;
1103
1118
  }
1104
 
  struct ifreq ifr;
1105
 
  strcpy(ifr.ifr_name, if_entry->d_name);
1106
 
  ret = ioctl(s, SIOCGIFFLAGS, &ifr);
 
1119
  strcpy(ifr->ifr_name, ifname);
 
1120
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1107
1121
  if(ret == -1){
1108
1122
    if(debug){
1109
1123
      perror_plus("ioctl SIOCGIFFLAGS");
1110
1124
    }
1111
 
    return 0;
 
1125
    return false;
1112
1126
  }
 
1127
  return true;
 
1128
}
 
1129
 
 
1130
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1131
  
1113
1132
  /* Reject the loopback device */
1114
 
  if(ifr.ifr_flags & IFF_LOOPBACK){
 
1133
  if(ifr->ifr_flags & IFF_LOOPBACK){
1115
1134
    if(debug){
1116
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1117
 
              if_entry->d_name);
 
1135
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1136
                   ifname);
1118
1137
    }
1119
 
    return 0;
 
1138
    return false;
1120
1139
  }
1121
1140
  /* Accept point-to-point devices only if connect_to is specified */
1122
 
  if(connect_to != NULL and (ifr.ifr_flags & IFF_POINTOPOINT)){
 
1141
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1123
1142
    if(debug){
1124
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1125
 
              if_entry->d_name);
 
1143
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1144
                   " \"%s\"\n", ifname);
1126
1145
    }
1127
 
    return 1;
 
1146
    return true;
1128
1147
  }
1129
1148
  /* Otherwise, reject non-broadcast-capable devices */
1130
 
  if(not (ifr.ifr_flags & IFF_BROADCAST)){
 
1149
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1131
1150
    if(debug){
1132
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1133
 
              if_entry->d_name);
 
1151
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1152
                   " \"%s\"\n", ifname);
1134
1153
    }
1135
 
    return 0;
 
1154
    return false;
1136
1155
  }
1137
1156
  /* Reject non-ARP interfaces (including dummy interfaces) */
1138
 
  if(ifr.ifr_flags & IFF_NOARP){
 
1157
  if(ifr->ifr_flags & IFF_NOARP){
1139
1158
    if(debug){
1140
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1141
 
              if_entry->d_name);
 
1159
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1160
                   ifname);
1142
1161
    }
1143
 
    return 0;
 
1162
    return false;
1144
1163
  }
 
1164
  
1145
1165
  /* Accept this device */
1146
1166
  if(debug){
1147
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1148
 
            if_entry->d_name);
 
1167
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1168
  }
 
1169
  return true;
 
1170
}
 
1171
 
 
1172
/* 
 
1173
 * This function determines if a directory entry in /sys/class/net
 
1174
 * corresponds to an acceptable network device.
 
1175
 * (This function is passed to scandir(3) as a filter function.)
 
1176
 */
 
1177
int good_interface(const struct dirent *if_entry){
 
1178
  if(if_entry->d_name[0] == '.'){
 
1179
    return 0;
 
1180
  }
 
1181
  
 
1182
  struct ifreq ifr;
 
1183
  if(not get_flags(if_entry->d_name, &ifr)){
 
1184
    if(debug){
 
1185
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1186
                   "\"%s\"\n", if_entry->d_name);
 
1187
    }
 
1188
    return 0;
 
1189
  }
 
1190
  
 
1191
  if(not good_flags(if_entry->d_name, &ifr)){
 
1192
    return 0;
 
1193
  }
 
1194
  return 1;
 
1195
}
 
1196
 
 
1197
/* 
 
1198
 * This function determines if a directory entry in /sys/class/net
 
1199
 * corresponds to an acceptable network device which is up.
 
1200
 * (This function is passed to scandir(3) as a filter function.)
 
1201
 */
 
1202
int up_interface(const struct dirent *if_entry){
 
1203
  if(if_entry->d_name[0] == '.'){
 
1204
    return 0;
 
1205
  }
 
1206
  
 
1207
  struct ifreq ifr;
 
1208
  if(not get_flags(if_entry->d_name, &ifr)){
 
1209
    if(debug){
 
1210
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1211
                   "\"%s\"\n", if_entry->d_name);
 
1212
    }
 
1213
    return 0;
 
1214
  }
 
1215
  
 
1216
  /* Reject down interfaces */
 
1217
  if(not (ifr.ifr_flags & IFF_UP)){
 
1218
    if(debug){
 
1219
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1220
                   if_entry->d_name);
 
1221
    }
 
1222
    return 0;
 
1223
  }
 
1224
  
 
1225
  /* Reject non-running interfaces */
 
1226
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1227
    if(debug){
 
1228
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1229
                   if_entry->d_name);
 
1230
    }
 
1231
    return 0;
 
1232
  }
 
1233
  
 
1234
  if(not good_flags(if_entry->d_name, &ifr)){
 
1235
    return 0;
1149
1236
  }
1150
1237
  return 1;
1151
1238
}
1161
1248
  return 1;
1162
1249
}
1163
1250
 
 
1251
/* Is this directory entry a runnable program? */
 
1252
int runnable_hook(const struct dirent *direntry){
 
1253
  int ret;
 
1254
  size_t sret;
 
1255
  struct stat st;
 
1256
  
 
1257
  if((direntry->d_name)[0] == '\0'){
 
1258
    /* Empty name? */
 
1259
    return 0;
 
1260
  }
 
1261
  
 
1262
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1263
                "abcdefghijklmnopqrstuvwxyz"
 
1264
                "0123456789"
 
1265
                "_-");
 
1266
  if((direntry->d_name)[sret] != '\0'){
 
1267
    /* Contains non-allowed characters */
 
1268
    if(debug){
 
1269
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1270
                   direntry->d_name);
 
1271
    }
 
1272
    return 0;
 
1273
  }
 
1274
  
 
1275
  char *fullname = NULL;
 
1276
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1277
  if(ret < 0){
 
1278
    perror_plus("asprintf");
 
1279
    return 0;
 
1280
  }
 
1281
  
 
1282
  ret = stat(fullname, &st);
 
1283
  if(ret == -1){
 
1284
    if(debug){
 
1285
      perror_plus("Could not stat hook");
 
1286
    }
 
1287
    return 0;
 
1288
  }
 
1289
  if(not (S_ISREG(st.st_mode))){
 
1290
    /* Not a regular file */
 
1291
    if(debug){
 
1292
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1293
                   direntry->d_name);
 
1294
    }
 
1295
    return 0;
 
1296
  }
 
1297
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1298
    /* Not executable */
 
1299
    if(debug){
 
1300
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1301
                   direntry->d_name);
 
1302
    }
 
1303
    return 0;
 
1304
  }
 
1305
  if(debug){
 
1306
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1307
                 direntry->d_name);
 
1308
  }
 
1309
  return 1;
 
1310
}
 
1311
 
1164
1312
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1165
1313
  int ret;
1166
1314
  struct timespec now;
1170
1318
  while(true){
1171
1319
    if(mc.current_server == NULL){
1172
1320
      if (debug){
1173
 
        fprintf(stderr,
1174
 
                "Wait until first server is found. No timeout!\n");
 
1321
        fprintf_plus(stderr, "Wait until first server is found."
 
1322
                     " No timeout!\n");
1175
1323
      }
1176
1324
      ret = avahi_simple_poll_iterate(s, -1);
1177
1325
    } else {
1178
1326
      if (debug){
1179
 
        fprintf(stderr, "Check current_server if we should run it,"
1180
 
                " or wait\n");
 
1327
        fprintf_plus(stderr, "Check current_server if we should run"
 
1328
                     " it, or wait\n");
1181
1329
      }
1182
1330
      /* the current time */
1183
1331
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1199
1347
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1200
1348
      
1201
1349
      if (debug){
1202
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1350
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1351
                     block_time);
1203
1352
      }
1204
1353
      
1205
1354
      if(block_time <= 0){
1225
1374
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1226
1375
    }
1227
1376
    if(ret != 0){
1228
 
      if (ret > 0 or errno != EINTR) {
 
1377
      if (ret > 0 or errno != EINTR){
1229
1378
        return (ret != 1) ? ret : 0;
1230
1379
      }
1231
1380
    }
1232
1381
  }
1233
1382
}
1234
1383
 
 
1384
bool run_network_hooks(const char *mode, const char *interface,
 
1385
                       const float delay){
 
1386
  struct dirent **direntries;
 
1387
  struct dirent *direntry;
 
1388
  int ret;
 
1389
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1390
                         alphasort);
 
1391
  if(numhooks == -1){
 
1392
    perror_plus("scandir");
 
1393
  } else {
 
1394
    int devnull = open("/dev/null", O_RDONLY);
 
1395
    for(int i = 0; i < numhooks; i++){
 
1396
      direntry = direntries[i];
 
1397
      char *fullname = NULL;
 
1398
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1399
      if(ret < 0){
 
1400
        perror_plus("asprintf");
 
1401
        continue;
 
1402
      }
 
1403
      if(debug){
 
1404
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1405
                     direntry->d_name);
 
1406
      }
 
1407
      pid_t hook_pid = fork();
 
1408
      if(hook_pid == 0){
 
1409
        /* Child */
 
1410
        /* Raise privileges */
 
1411
        errno = 0;
 
1412
        ret = seteuid(0);
 
1413
        if(ret == -1){
 
1414
          perror_plus("seteuid");
 
1415
        }
 
1416
        /* Raise privileges even more */
 
1417
        errno = 0;
 
1418
        ret = setuid(0);
 
1419
        if(ret == -1){
 
1420
          perror_plus("setuid");
 
1421
        }
 
1422
        /* Set group */
 
1423
        errno = 0;
 
1424
        ret = setgid(0);
 
1425
        if(ret == -1){
 
1426
          perror_plus("setgid");
 
1427
        }
 
1428
        /* Reset supplementary groups */
 
1429
        errno = 0;
 
1430
        ret = setgroups(0, NULL);
 
1431
        if(ret == -1){
 
1432
          perror_plus("setgroups");
 
1433
        }
 
1434
        dup2(devnull, STDIN_FILENO);
 
1435
        close(devnull);
 
1436
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1437
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1438
        if(ret == -1){
 
1439
          perror_plus("setenv");
 
1440
          _exit(EX_OSERR);
 
1441
        }
 
1442
        ret = setenv("DEVICE", interface, 1);
 
1443
        if(ret == -1){
 
1444
          perror_plus("setenv");
 
1445
          _exit(EX_OSERR);
 
1446
        }
 
1447
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1448
        if(ret == -1){
 
1449
          perror_plus("setenv");
 
1450
          _exit(EX_OSERR);
 
1451
        }
 
1452
        ret = setenv("MODE", mode, 1);
 
1453
        if(ret == -1){
 
1454
          perror_plus("setenv");
 
1455
          _exit(EX_OSERR);
 
1456
        }
 
1457
        char *delaystring;
 
1458
        ret = asprintf(&delaystring, "%f", delay);
 
1459
        if(ret == -1){
 
1460
          perror_plus("asprintf");
 
1461
          _exit(EX_OSERR);
 
1462
        }
 
1463
        ret = setenv("DELAY", delaystring, 1);
 
1464
        if(ret == -1){
 
1465
          free(delaystring);
 
1466
          perror_plus("setenv");
 
1467
          _exit(EX_OSERR);
 
1468
        }
 
1469
        free(delaystring);
 
1470
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1471
        perror_plus("execl");
 
1472
      } else {
 
1473
        int status;
 
1474
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1475
          perror_plus("waitpid");
 
1476
          free(fullname);
 
1477
          continue;
 
1478
        }
 
1479
        if(WIFEXITED(status)){
 
1480
          if(WEXITSTATUS(status) != 0){
 
1481
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1482
                         " with status %d\n", direntry->d_name,
 
1483
                         WEXITSTATUS(status));
 
1484
            free(fullname);
 
1485
            continue;
 
1486
          }
 
1487
        } else if(WIFSIGNALED(status)){
 
1488
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1489
                       " signal %d\n", direntry->d_name,
 
1490
                       WTERMSIG(status));
 
1491
          free(fullname);
 
1492
          continue;
 
1493
        } else {
 
1494
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1495
                       " crashed\n", direntry->d_name);
 
1496
          free(fullname);
 
1497
          continue;
 
1498
        }
 
1499
      }
 
1500
      free(fullname);
 
1501
      if(debug){
 
1502
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1503
                     direntry->d_name);
 
1504
      }
 
1505
    }
 
1506
    close(devnull);
 
1507
  }
 
1508
  return true;
 
1509
}
 
1510
 
1235
1511
int main(int argc, char *argv[]){
1236
1512
  AvahiSServiceBrowser *sb = NULL;
1237
1513
  int error;
1319
1595
        .arg = "SECONDS",
1320
1596
        .doc = "Retry interval used when denied by the mandos server",
1321
1597
        .group = 2 },
 
1598
      { .name = "network-hook-dir", .key = 133,
 
1599
        .arg = "DIR",
 
1600
        .doc = "Directory where network hooks are located",
 
1601
        .group = 2 },
1322
1602
      /*
1323
1603
       * These reproduce what we would get without ARGP_NO_HELP
1324
1604
       */
1377
1657
          argp_error(state, "Bad retry interval");
1378
1658
        }
1379
1659
        break;
 
1660
      case 133:                 /* --network-hook-dir */
 
1661
        hookdir = arg;
 
1662
        break;
1380
1663
        /*
1381
1664
         * These reproduce what we would get without ARGP_NO_HELP
1382
1665
         */
1388
1671
        argp_state_help(state, state->out_stream,
1389
1672
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1390
1673
      case 'V':                 /* --version */
1391
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1674
        fprintf_plus(state->out_stream,
 
1675
                     "Mandos plugin mandos-client: ");
 
1676
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1392
1677
        exit(argp_err_exit_status);
1393
1678
        break;
1394
1679
      default:
1421
1706
  {
1422
1707
    /* Work around Debian bug #633582:
1423
1708
       <http://bugs.debian.org/633582> */
1424
 
    struct stat st;
1425
1709
    
1426
1710
    /* Re-raise priviliges */
1427
1711
    errno = 0;
1428
1712
    ret = seteuid(0);
1429
1713
    if(ret == -1){
1430
1714
      perror_plus("seteuid");
1431
 
    }
1432
 
    
1433
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1434
 
      int seckey_fd = open(seckey, O_RDONLY);
1435
 
      if(seckey_fd == -1){
1436
 
        perror_plus("open");
1437
 
      } else {
1438
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1439
 
        if(ret == -1){
1440
 
          perror_plus("fstat");
1441
 
        } else {
1442
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1443
 
            ret = fchown(seckey_fd, uid, gid);
1444
 
            if(ret == -1){
1445
 
              perror_plus("fchown");
1446
 
            }
1447
 
          }
1448
 
        }
1449
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1450
 
      }
1451
 
    }
1452
 
    
1453
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1454
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1455
 
      if(pubkey_fd == -1){
1456
 
        perror_plus("open");
1457
 
      } else {
1458
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1459
 
        if(ret == -1){
1460
 
          perror_plus("fstat");
1461
 
        } else {
1462
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1463
 
            ret = fchown(pubkey_fd, uid, gid);
1464
 
            if(ret == -1){
1465
 
              perror_plus("fchown");
1466
 
            }
1467
 
          }
1468
 
        }
1469
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1470
 
      }
1471
 
    }
1472
 
    
1473
 
    /* Lower privileges */
1474
 
    errno = 0;
1475
 
    ret = seteuid(uid);
1476
 
    if(ret == -1){
1477
 
      perror_plus("seteuid");
1478
 
    }
 
1715
    } else {
 
1716
      struct stat st;
 
1717
      
 
1718
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1719
        int seckey_fd = open(seckey, O_RDONLY);
 
1720
        if(seckey_fd == -1){
 
1721
          perror_plus("open");
 
1722
        } else {
 
1723
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1724
          if(ret == -1){
 
1725
            perror_plus("fstat");
 
1726
          } else {
 
1727
            if(S_ISREG(st.st_mode)
 
1728
               and st.st_uid == 0 and st.st_gid == 0){
 
1729
              ret = fchown(seckey_fd, uid, gid);
 
1730
              if(ret == -1){
 
1731
                perror_plus("fchown");
 
1732
              }
 
1733
            }
 
1734
          }
 
1735
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1736
        }
 
1737
      }
 
1738
    
 
1739
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1740
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1741
        if(pubkey_fd == -1){
 
1742
          perror_plus("open");
 
1743
        } else {
 
1744
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1745
          if(ret == -1){
 
1746
            perror_plus("fstat");
 
1747
          } else {
 
1748
            if(S_ISREG(st.st_mode)
 
1749
               and st.st_uid == 0 and st.st_gid == 0){
 
1750
              ret = fchown(pubkey_fd, uid, gid);
 
1751
              if(ret == -1){
 
1752
                perror_plus("fchown");
 
1753
              }
 
1754
            }
 
1755
          }
 
1756
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1757
        }
 
1758
      }
 
1759
    
 
1760
      /* Lower privileges */
 
1761
      errno = 0;
 
1762
      ret = seteuid(uid);
 
1763
      if(ret == -1){
 
1764
        perror_plus("seteuid");
 
1765
      }
 
1766
    }
 
1767
  }
 
1768
  
 
1769
  /* Run network hooks */
 
1770
  if(not run_network_hooks("start", interface, delay)){
 
1771
    goto end;
1479
1772
  }
1480
1773
  
1481
1774
  if(not debug){
1482
1775
    avahi_set_log_function(empty_log);
1483
1776
  }
1484
 
 
 
1777
  
1485
1778
  if(interface[0] == '\0'){
1486
1779
    struct dirent **direntries;
1487
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1780
    /* First look for interfaces that are up */
 
1781
    ret = scandir(sys_class_net, &direntries, up_interface,
1488
1782
                  alphasort);
 
1783
    if(ret == 0){
 
1784
      /* No up interfaces, look for any good interfaces */
 
1785
      free(direntries);
 
1786
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1787
                    alphasort);
 
1788
    }
1489
1789
    if(ret >= 1){
1490
 
      /* Pick the first good interface */
 
1790
      /* Pick the first interface returned */
1491
1791
      interface = strdup(direntries[0]->d_name);
1492
1792
      if(debug){
1493
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1793
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1494
1794
      }
1495
1795
      if(interface == NULL){
1496
1796
        perror_plus("malloc");
1501
1801
      free(direntries);
1502
1802
    } else {
1503
1803
      free(direntries);
1504
 
      fprintf(stderr, "Could not find a network interface\n");
 
1804
      fprintf_plus(stderr, "Could not find a network interface\n");
1505
1805
      exitcode = EXIT_FAILURE;
1506
1806
      goto end;
1507
1807
    }
1513
1813
  srand((unsigned int) time(NULL));
1514
1814
  mc.simple_poll = avahi_simple_poll_new();
1515
1815
  if(mc.simple_poll == NULL){
1516
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1816
    fprintf_plus(stderr,
 
1817
                 "Avahi: Failed to create simple poll object.\n");
1517
1818
    exitcode = EX_UNAVAILABLE;
1518
1819
    goto end;
1519
1820
  }
1585
1886
  if(strcmp(interface, "none") != 0){
1586
1887
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1587
1888
    if(if_index == 0){
1588
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1889
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1589
1890
      exitcode = EX_UNAVAILABLE;
1590
1891
      goto end;
1591
1892
    }
1711
2012
#endif  /* __linux__ */
1712
2013
    /* Lower privileges */
1713
2014
    errno = 0;
1714
 
    if(take_down_interface){
1715
 
      /* Lower privileges */
1716
 
      ret = seteuid(uid);
1717
 
      if(ret == -1){
1718
 
        perror_plus("seteuid");
1719
 
      }
1720
 
    } else {
1721
 
      /* Lower privileges permanently */
1722
 
      ret = setuid(uid);
1723
 
      if(ret == -1){
1724
 
        perror_plus("setuid");
1725
 
      }
 
2015
    /* Lower privileges */
 
2016
    ret = seteuid(uid);
 
2017
    if(ret == -1){
 
2018
      perror_plus("seteuid");
1726
2019
    }
1727
2020
  }
1728
2021
  
1732
2025
  
1733
2026
  ret = init_gnutls_global(pubkey, seckey);
1734
2027
  if(ret == -1){
1735
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2028
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1736
2029
    exitcode = EX_UNAVAILABLE;
1737
2030
    goto end;
1738
2031
  } else {
1754
2047
  }
1755
2048
  
1756
2049
  if(not init_gpgme(pubkey, seckey, tempdir)){
1757
 
    fprintf(stderr, "init_gpgme failed\n");
 
2050
    fprintf_plus(stderr, "init_gpgme failed\n");
1758
2051
    exitcode = EX_UNAVAILABLE;
1759
2052
    goto end;
1760
2053
  } else {
1770
2063
    /* (Mainly meant for debugging) */
1771
2064
    char *address = strrchr(connect_to, ':');
1772
2065
    if(address == NULL){
1773
 
      fprintf(stderr, "No colon in address\n");
 
2066
      fprintf_plus(stderr, "No colon in address\n");
1774
2067
      exitcode = EX_USAGE;
1775
2068
      goto end;
1776
2069
    }
1784
2077
    tmpmax = strtoimax(address+1, &tmp, 10);
1785
2078
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1786
2079
       or tmpmax != (uint16_t)tmpmax){
1787
 
      fprintf(stderr, "Bad port number\n");
 
2080
      fprintf_plus(stderr, "Bad port number\n");
1788
2081
      exitcode = EX_USAGE;
1789
2082
      goto end;
1790
2083
    }
1820
2113
        break;
1821
2114
      }
1822
2115
      if(debug){
1823
 
        fprintf(stderr, "Retrying in %d seconds\n",
1824
 
                (int)retry_interval);
 
2116
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2117
                     (int)retry_interval);
1825
2118
      }
1826
2119
      sleep((int)retry_interval);
1827
2120
    }
1829
2122
    if (not quit_now){
1830
2123
      exitcode = EXIT_SUCCESS;
1831
2124
    }
1832
 
 
 
2125
    
1833
2126
    goto end;
1834
2127
  }
1835
2128
  
1857
2150
  
1858
2151
  /* Check if creating the Avahi server object succeeded */
1859
2152
  if(mc.server == NULL){
1860
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1861
 
            avahi_strerror(error));
 
2153
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2154
                 avahi_strerror(error));
1862
2155
    exitcode = EX_UNAVAILABLE;
1863
2156
    goto end;
1864
2157
  }
1872
2165
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1873
2166
                                   NULL, 0, browse_callback, NULL);
1874
2167
  if(sb == NULL){
1875
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1876
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2168
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2169
                 avahi_strerror(avahi_server_errno(mc.server)));
1877
2170
    exitcode = EX_UNAVAILABLE;
1878
2171
    goto end;
1879
2172
  }
1885
2178
  /* Run the main loop */
1886
2179
  
1887
2180
  if(debug){
1888
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2181
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1889
2182
  }
1890
2183
 
1891
2184
  ret = avahi_loop_with_timeout(mc.simple_poll,
1892
2185
                                (int)(retry_interval * 1000));
1893
2186
  if(debug){
1894
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1895
 
            (ret == 0) ? "successfully" : "with error");
 
2187
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2188
                 (ret == 0) ? "successfully" : "with error");
1896
2189
  }
1897
2190
  
1898
2191
 end:
1899
2192
  
1900
2193
  if(debug){
1901
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2194
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1902
2195
  }
1903
2196
  
1904
2197
  /* Cleanup things */
1920
2213
  if(gpgme_initialized){
1921
2214
    gpgme_release(mc.ctx);
1922
2215
  }
1923
 
 
 
2216
  
1924
2217
  /* Cleans up the circular linked list of Mandos servers the client
1925
2218
     has seen */
1926
2219
  if(mc.current_server != NULL){
1932
2225
    }
1933
2226
  }
1934
2227
  
1935
 
  /* Take down the network interface */
1936
 
  if(take_down_interface){
1937
 
    /* Re-raise priviliges */
 
2228
  /* Run network hooks */
 
2229
  run_network_hooks("stop", interface, delay);
 
2230
  
 
2231
  /* Re-raise priviliges */
 
2232
  {
1938
2233
    errno = 0;
1939
2234
    ret = seteuid(0);
1940
2235
    if(ret == -1){
1941
2236
      perror_plus("seteuid");
1942
2237
    }
1943
 
    if(geteuid() == 0){
 
2238
    
 
2239
    /* Take down the network interface */
 
2240
    if(take_down_interface and geteuid() == 0){
1944
2241
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1945
2242
      if(ret == -1){
1946
2243
        perror_plus("ioctl SIOCGIFFLAGS");
1947
 
      } else if(network.ifr_flags & IFF_UP) {
 
2244
      } else if(network.ifr_flags & IFF_UP){
1948
2245
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1949
2246
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1950
2247
        if(ret == -1){
1955
2252
      if(ret == -1){
1956
2253
        perror_plus("close");
1957
2254
      }
1958
 
      /* Lower privileges permanently */
1959
 
      errno = 0;
1960
 
      ret = setuid(uid);
1961
 
      if(ret == -1){
1962
 
        perror_plus("setuid");
1963
 
      }
1964
2255
    }
1965
2256
  }
 
2257
  /* Lower privileges permanently */
 
2258
  errno = 0;
 
2259
  ret = setuid(uid);
 
2260
  if(ret == -1){
 
2261
    perror_plus("setuid");
 
2262
  }
1966
2263
  
1967
2264
  /* Removes the GPGME temp directory and all files inside */
1968
2265
  if(tempdir_created){
1982
2279
        }
1983
2280
        ret = remove(fullname);
1984
2281
        if(ret == -1){
1985
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1986
 
                  strerror(errno));
 
2282
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2283
                       strerror(errno));
1987
2284
        }
1988
2285
        free(fullname);
1989
2286
      }