/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: teddy at bsnet
  • Date: 2011-12-24 23:17:02 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111224231702-1ffgu6r02p0bz9co
* plugins.d/splashy.c (error_plus): Check format string.
* plugins.d/askpass-fifo.c (error_plus): - '' -
* plugins.d/plymouth.c (error_plus): - '' -
* plugins.d/password-prompt.c (error_plus): - '' -
* plugins.d/usplash.c (error_plus): - '' -

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
__attribute__((format (gnu_printf, 2, 3)))
 
179
int fprintf_plus(FILE *stream, const char *format, ...){
 
180
  va_list ap;
 
181
  va_start (ap, format);
 
182
  
 
183
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
184
                             program_invocation_short_name));
 
185
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
186
}
 
187
 
173
188
/*
174
189
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
190
 * bytes. "buffer_capacity" is how much is currently allocated,
176
191
 * "buffer_length" is how much is already used.
177
192
 */
178
193
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
194
                 size_t buffer_capacity){
180
195
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
196
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
197
    if(buffer == NULL){
188
203
}
189
204
 
190
205
/* 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){
 
206
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
207
                int af){
194
208
  int ret;
195
209
  server *new_server = malloc(sizeof(server));
196
210
  if(new_server == NULL){
197
211
    perror_plus("malloc");
198
 
    return -1;
 
212
    return false;
199
213
  }
200
214
  *new_server = (server){ .ip = strdup(ip),
201
 
                         .port = port,
202
 
                         .if_index = if_index,
203
 
                         .af = af };
 
215
                          .port = port,
 
216
                          .if_index = if_index,
 
217
                          .af = af };
204
218
  if(new_server->ip == NULL){
205
219
    perror_plus("strdup");
206
 
    return -1;
 
220
    return false;
207
221
  }
208
222
  /* Special case of first server */
209
223
  if (mc.current_server == NULL){
220
234
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
221
235
  if(ret == -1){
222
236
    perror_plus("clock_gettime");
223
 
    return -1;
 
237
    return false;
224
238
  }
225
 
  return 0;
 
239
  return true;
226
240
}
227
241
 
228
242
/* 
229
243
 * Initialize GPGME.
230
244
 */
231
 
static bool init_gpgme(const char *seckey,
232
 
                       const char *pubkey, const char *tempdir){
 
245
static bool init_gpgme(const char *seckey, const char *pubkey,
 
246
                       const char *tempdir){
233
247
  gpgme_error_t rc;
234
248
  gpgme_engine_info_t engine_info;
235
249
  
250
264
    
251
265
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
252
266
    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));
 
267
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
268
                   gpgme_strsource(rc), gpgme_strerror(rc));
255
269
      return false;
256
270
    }
257
271
    
258
272
    rc = gpgme_op_import(mc.ctx, pgp_data);
259
273
    if(rc != GPG_ERR_NO_ERROR){
260
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
261
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
274
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
275
                   gpgme_strsource(rc), gpgme_strerror(rc));
262
276
      return false;
263
277
    }
264
278
    
271
285
  }
272
286
  
273
287
  if(debug){
274
 
    fprintf(stderr, "Initializing GPGME\n");
 
288
    fprintf_plus(stderr, "Initializing GPGME\n");
275
289
  }
276
290
  
277
291
  /* Init GPGME */
278
292
  gpgme_check_version(NULL);
279
293
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
280
294
  if(rc != GPG_ERR_NO_ERROR){
281
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
282
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
295
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
296
                 gpgme_strsource(rc), gpgme_strerror(rc));
283
297
    return false;
284
298
  }
285
299
  
286
300
  /* Set GPGME home directory for the OpenPGP engine only */
287
301
  rc = gpgme_get_engine_info(&engine_info);
288
302
  if(rc != GPG_ERR_NO_ERROR){
289
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
290
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
303
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
304
                 gpgme_strsource(rc), gpgme_strerror(rc));
291
305
    return false;
292
306
  }
293
307
  while(engine_info != NULL){
299
313
    engine_info = engine_info->next;
300
314
  }
301
315
  if(engine_info == NULL){
302
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
316
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
317
                 tempdir);
303
318
    return false;
304
319
  }
305
320
  
306
321
  /* Create new GPGME "context" */
307
322
  rc = gpgme_new(&(mc.ctx));
308
323
  if(rc != GPG_ERR_NO_ERROR){
309
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
310
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
324
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
325
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
326
                 gpgme_strerror(rc));
311
327
    return false;
312
328
  }
313
329
  
332
348
  ssize_t plaintext_length = 0;
333
349
  
334
350
  if(debug){
335
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
351
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
336
352
  }
337
353
  
338
354
  /* Create new GPGME data buffer from memory cryptotext */
339
355
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
340
356
                               0);
341
357
  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));
 
358
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
359
                 gpgme_strsource(rc), gpgme_strerror(rc));
344
360
    return -1;
345
361
  }
346
362
  
347
363
  /* Create new empty GPGME data buffer for the plaintext */
348
364
  rc = gpgme_data_new(&dh_plain);
349
365
  if(rc != GPG_ERR_NO_ERROR){
350
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
351
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
366
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
367
                 "bad gpgme_data_new: %s: %s\n",
 
368
                 gpgme_strsource(rc), gpgme_strerror(rc));
352
369
    gpgme_data_release(dh_crypto);
353
370
    return -1;
354
371
  }
357
374
     data buffer */
358
375
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
359
376
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
361
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
377
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
378
                 gpgme_strsource(rc), gpgme_strerror(rc));
362
379
    plaintext_length = -1;
363
380
    if(debug){
364
381
      gpgme_decrypt_result_t result;
365
382
      result = gpgme_op_decrypt_result(mc.ctx);
366
383
      if(result == NULL){
367
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
384
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
368
385
      } 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);
 
386
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
387
                     result->unsupported_algorithm);
 
388
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
389
                     result->wrong_key_usage);
373
390
        if(result->file_name != NULL){
374
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
391
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
375
392
        }
376
393
        gpgme_recipient_t recipient;
377
394
        recipient = result->recipients;
378
395
        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");
 
396
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
397
                       gpgme_pubkey_algo_name
 
398
                       (recipient->pubkey_algo));
 
399
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
400
          fprintf_plus(stderr, "Secret key available: %s\n",
 
401
                       recipient->status == GPG_ERR_NO_SECKEY
 
402
                       ? "No" : "Yes");
385
403
          recipient = recipient->next;
386
404
        }
387
405
      }
390
408
  }
391
409
  
392
410
  if(debug){
393
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
411
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
394
412
  }
395
413
  
396
414
  /* Seek back to the beginning of the GPGME plaintext data buffer */
403
421
  *plaintext = NULL;
404
422
  while(true){
405
423
    plaintext_capacity = incbuffer(plaintext,
406
 
                                      (size_t)plaintext_length,
407
 
                                      plaintext_capacity);
 
424
                                   (size_t)plaintext_length,
 
425
                                   plaintext_capacity);
408
426
    if(plaintext_capacity == 0){
409
 
        perror_plus("incbuffer");
410
 
        plaintext_length = -1;
411
 
        goto decrypt_end;
 
427
      perror_plus("incbuffer");
 
428
      plaintext_length = -1;
 
429
      goto decrypt_end;
412
430
    }
413
431
    
414
432
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
427
445
  }
428
446
  
429
447
  if(debug){
430
 
    fprintf(stderr, "Decrypted password is: ");
 
448
    fprintf_plus(stderr, "Decrypted password is: ");
431
449
    for(ssize_t i = 0; i < plaintext_length; i++){
432
450
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
433
451
    }
455
473
/* GnuTLS log function callback */
456
474
static void debuggnutls(__attribute__((unused)) int level,
457
475
                        const char* string){
458
 
  fprintf(stderr, "GnuTLS: %s", string);
 
476
  fprintf_plus(stderr, "GnuTLS: %s", string);
459
477
}
460
478
 
461
479
static int init_gnutls_global(const char *pubkeyfilename,
463
481
  int ret;
464
482
  
465
483
  if(debug){
466
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
484
    fprintf_plus(stderr, "Initializing GnuTLS\n");
467
485
  }
468
486
  
469
487
  ret = gnutls_global_init();
470
488
  if(ret != GNUTLS_E_SUCCESS){
471
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
472
 
            safer_gnutls_strerror(ret));
 
489
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
490
                 safer_gnutls_strerror(ret));
473
491
    return -1;
474
492
  }
475
493
  
484
502
  /* OpenPGP credentials */
485
503
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
486
504
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
488
 
            safer_gnutls_strerror(ret));
 
505
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
506
                 safer_gnutls_strerror(ret));
489
507
    gnutls_global_deinit();
490
508
    return -1;
491
509
  }
492
510
  
493
511
  if(debug){
494
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
495
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
496
 
            seckeyfilename);
 
512
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
513
                 " secret key %s as GnuTLS credentials\n",
 
514
                 pubkeyfilename,
 
515
                 seckeyfilename);
497
516
  }
498
517
  
499
518
  ret = gnutls_certificate_set_openpgp_key_file
500
519
    (mc.cred, pubkeyfilename, seckeyfilename,
501
520
     GNUTLS_OPENPGP_FMT_BASE64);
502
521
  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));
 
522
    fprintf_plus(stderr,
 
523
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
524
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
525
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
526
                 safer_gnutls_strerror(ret));
508
527
    goto globalfail;
509
528
  }
510
529
  
511
530
  /* GnuTLS server initialization */
512
531
  ret = gnutls_dh_params_init(&mc.dh_params);
513
532
  if(ret != GNUTLS_E_SUCCESS){
514
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
515
 
            " %s\n", safer_gnutls_strerror(ret));
 
533
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
534
                 " initialization: %s\n",
 
535
                 safer_gnutls_strerror(ret));
516
536
    goto globalfail;
517
537
  }
518
538
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
519
539
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
521
 
            safer_gnutls_strerror(ret));
 
540
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
541
                 safer_gnutls_strerror(ret));
522
542
    goto globalfail;
523
543
  }
524
544
  
544
564
    }
545
565
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
546
566
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
548
 
            safer_gnutls_strerror(ret));
 
567
    fprintf_plus(stderr,
 
568
                 "Error in GnuTLS session initialization: %s\n",
 
569
                 safer_gnutls_strerror(ret));
549
570
  }
550
571
  
551
572
  {
558
579
      }
559
580
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
560
581
    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));
 
582
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
583
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
584
                   safer_gnutls_strerror(ret));
564
585
      gnutls_deinit(*session);
565
586
      return -1;
566
587
    }
575
596
    }
576
597
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
577
598
  if(ret != GNUTLS_E_SUCCESS){
578
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
579
 
            safer_gnutls_strerror(ret));
 
599
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
600
                 safer_gnutls_strerror(ret));
580
601
    gnutls_deinit(*session);
581
602
    return -1;
582
603
  }
627
648
    pf = PF_INET;
628
649
    break;
629
650
  default:
630
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
651
    fprintf_plus(stderr, "Bad address family: %d\n", af);
631
652
    errno = EINVAL;
632
653
    return -1;
633
654
  }
638
659
  }
639
660
  
640
661
  if(debug){
641
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
642
 
            "\n", ip, port);
 
662
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
663
                 PRIu16 "\n", ip, port);
643
664
  }
644
665
  
645
666
  tcp_sd = socket(pf, SOCK_STREAM, 0);
671
692
  }
672
693
  if(ret == 0){
673
694
    int e = errno;
674
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
695
    fprintf_plus(stderr, "Bad address: %s\n", ip);
675
696
    errno = e;
676
697
    goto mandos_end;
677
698
  }
682
703
    
683
704
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
684
705
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
685
 
                              -Wunreachable-code*/
 
706
                                -Wunreachable-code*/
686
707
      if(if_index == AVAHI_IF_UNSPEC){
687
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
688
 
                " without a network interface\n");
 
708
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
709
                     " incomplete without a network interface\n");
689
710
        errno = EINVAL;
690
711
        goto mandos_end;
691
712
      }
709
730
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
731
        perror_plus("if_indextoname");
711
732
      } else {
712
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
713
 
                ip, interface, port);
 
733
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
734
                     "\n", ip, interface, port);
714
735
      }
715
736
    } else {
716
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
717
 
              port);
 
737
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
738
                   ip, port);
718
739
    }
719
740
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
720
741
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
730
751
      perror_plus("inet_ntop");
731
752
    } else {
732
753
      if(strcmp(addrstr, ip) != 0){
733
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
754
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
734
755
      }
735
756
    }
736
757
  }
764
785
  while(true){
765
786
    size_t out_size = strlen(out);
766
787
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
767
 
                                   out_size - written));
 
788
                                        out_size - written));
768
789
    if(ret == -1){
769
790
      int e = errno;
770
791
      perror_plus("write");
790
811
  }
791
812
  
792
813
  if(debug){
793
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
814
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
794
815
  }
795
816
  
796
817
  if(quit_now){
816
837
  
817
838
  if(ret != GNUTLS_E_SUCCESS){
818
839
    if(debug){
819
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
840
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
820
841
      gnutls_perror(ret);
821
842
    }
822
843
    errno = EPROTO;
826
847
  /* Read OpenPGP packet that contains the wanted password */
827
848
  
828
849
  if(debug){
829
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
830
 
            ip);
 
850
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
851
                 " %s\n", ip);
831
852
  }
832
853
  
833
854
  while(true){
838
859
    }
839
860
    
840
861
    buffer_capacity = incbuffer(&buffer, buffer_length,
841
 
                                   buffer_capacity);
 
862
                                buffer_capacity);
842
863
    if(buffer_capacity == 0){
843
864
      int e = errno;
844
865
      perror_plus("incbuffer");
871
892
          }
872
893
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
873
894
        if(ret < 0){
874
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
895
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
896
                       "***\n");
875
897
          gnutls_perror(ret);
876
898
          errno = EPROTO;
877
899
          goto mandos_end;
878
900
        }
879
901
        break;
880
902
      default:
881
 
        fprintf(stderr, "Unknown error while reading data from"
882
 
                " encrypted session with Mandos server\n");
 
903
        fprintf_plus(stderr, "Unknown error while reading data from"
 
904
                     " encrypted session with Mandos server\n");
883
905
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
884
906
        errno = EIO;
885
907
        goto mandos_end;
890
912
  }
891
913
  
892
914
  if(debug){
893
 
    fprintf(stderr, "Closing TLS session\n");
 
915
    fprintf_plus(stderr, "Closing TLS session\n");
894
916
  }
895
917
  
896
918
  if(quit_now){
908
930
  
909
931
  if(buffer_length > 0){
910
932
    ssize_t decrypted_buffer_size;
911
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
912
 
                                               buffer_length,
 
933
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
913
934
                                               &decrypted_buffer);
914
935
    if(decrypted_buffer_size >= 0){
915
936
      
926
947
        if(ret == 0 and ferror(stdout)){
927
948
          int e = errno;
928
949
          if(debug){
929
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
930
 
                    strerror(errno));
 
950
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
951
                         strerror(errno));
931
952
          }
932
953
          errno = e;
933
954
          goto mandos_end;
990
1011
  switch(event){
991
1012
  default:
992
1013
  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)));
 
1014
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1015
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1016
                 domain,
 
1017
                 avahi_strerror(avahi_server_errno(mc.server)));
996
1018
    break;
997
1019
    
998
1020
  case AVAHI_RESOLVER_FOUND:
1000
1022
      char ip[AVAHI_ADDRESS_STR_MAX];
1001
1023
      avahi_address_snprint(ip, sizeof(ip), address);
1002
1024
      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);
 
1025
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1026
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1027
                     host_name, ip, (intmax_t)interface, port);
1006
1028
      }
1007
1029
      int ret = start_mandos_communication(ip, port, interface,
1008
1030
                                           avahi_proto_to_af(proto));
1009
1031
      if(ret == 0){
1010
1032
        avahi_simple_poll_quit(mc.simple_poll);
1011
1033
      } else {
1012
 
        ret = add_server(ip, port, interface,
1013
 
                         avahi_proto_to_af(proto));
 
1034
        if(not add_server(ip, port, interface,
 
1035
                          avahi_proto_to_af(proto))){
 
1036
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1037
                       " list\n", name);
 
1038
        }
1014
1039
      }
1015
1040
    }
1016
1041
  }
1040
1065
  default:
1041
1066
  case AVAHI_BROWSER_FAILURE:
1042
1067
    
1043
 
    fprintf(stderr, "(Avahi browser) %s\n",
1044
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1068
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1069
                 avahi_strerror(avahi_server_errno(mc.server)));
1045
1070
    avahi_simple_poll_quit(mc.simple_poll);
1046
1071
    return;
1047
1072
    
1054
1079
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1055
1080
                                    name, type, domain, protocol, 0,
1056
1081
                                    resolve_callback, NULL) == NULL)
1057
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1058
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1082
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1083
                   " %s\n", name,
 
1084
                   avahi_strerror(avahi_server_errno(mc.server)));
1059
1085
    break;
1060
1086
    
1061
1087
  case AVAHI_BROWSER_REMOVE:
1064
1090
  case AVAHI_BROWSER_ALL_FOR_NOW:
1065
1091
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1066
1092
    if(debug){
1067
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1093
      fprintf_plus(stderr, "No Mandos server found, still"
 
1094
                   " searching...\n");
1068
1095
    }
1069
1096
    break;
1070
1097
  }
1085
1112
  errno = old_errno;
1086
1113
}
1087
1114
 
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){
 
1115
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1116
  int ret;
 
1117
  
 
1118
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1119
  if(s < 0){
 
1120
    perror_plus("socket");
 
1121
    return false;
 
1122
  }
 
1123
  strcpy(ifr->ifr_name, ifname);
 
1124
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1125
  if(ret == -1){
1144
1126
    if(debug){
1145
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1146
 
              flagstring, if_entry->d_name);
 
1127
      perror_plus("ioctl SIOCGIFFLAGS");
1147
1128
    }
1148
 
    free(flagstring);
1149
 
    return 0;
 
1129
    return false;
1150
1130
  }
1151
 
  free(flagstring);
1152
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1131
  return true;
 
1132
}
 
1133
 
 
1134
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1135
  
1153
1136
  /* Reject the loopback device */
1154
 
  if(flags & IFF_LOOPBACK){
 
1137
  if(ifr->ifr_flags & IFF_LOOPBACK){
1155
1138
    if(debug){
1156
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1157
 
              if_entry->d_name);
 
1139
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1140
                   ifname);
1158
1141
    }
1159
 
    return 0;
 
1142
    return false;
1160
1143
  }
1161
1144
  /* Accept point-to-point devices only if connect_to is specified */
1162
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1145
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1163
1146
    if(debug){
1164
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1165
 
              if_entry->d_name);
 
1147
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1148
                   " \"%s\"\n", ifname);
1166
1149
    }
1167
 
    return 1;
 
1150
    return true;
1168
1151
  }
1169
1152
  /* Otherwise, reject non-broadcast-capable devices */
1170
 
  if(not (flags & IFF_BROADCAST)){
 
1153
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1171
1154
    if(debug){
1172
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1173
 
              if_entry->d_name);
 
1155
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1156
                   " \"%s\"\n", ifname);
1174
1157
    }
1175
 
    return 0;
 
1158
    return false;
1176
1159
  }
1177
1160
  /* Reject non-ARP interfaces (including dummy interfaces) */
1178
 
  if(flags & IFF_NOARP){
 
1161
  if(ifr->ifr_flags & IFF_NOARP){
1179
1162
    if(debug){
1180
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1181
 
              if_entry->d_name);
 
1163
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1164
                   ifname);
1182
1165
    }
1183
 
    return 0;
 
1166
    return false;
1184
1167
  }
 
1168
  
1185
1169
  /* Accept this device */
1186
1170
  if(debug){
1187
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1188
 
            if_entry->d_name);
 
1171
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1172
  }
 
1173
  return true;
 
1174
}
 
1175
 
 
1176
/* 
 
1177
 * This function determines if a directory entry in /sys/class/net
 
1178
 * corresponds to an acceptable network device.
 
1179
 * (This function is passed to scandir(3) as a filter function.)
 
1180
 */
 
1181
int good_interface(const struct dirent *if_entry){
 
1182
  if(if_entry->d_name[0] == '.'){
 
1183
    return 0;
 
1184
  }
 
1185
  
 
1186
  struct ifreq ifr;
 
1187
  if(not get_flags(if_entry->d_name, &ifr)){
 
1188
    if(debug){
 
1189
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1190
                   "\"%s\"\n", if_entry->d_name);
 
1191
    }
 
1192
    return 0;
 
1193
  }
 
1194
  
 
1195
  if(not good_flags(if_entry->d_name, &ifr)){
 
1196
    return 0;
 
1197
  }
 
1198
  return 1;
 
1199
}
 
1200
 
 
1201
/* 
 
1202
 * This function determines if a directory entry in /sys/class/net
 
1203
 * corresponds to an acceptable network device which is up.
 
1204
 * (This function is passed to scandir(3) as a filter function.)
 
1205
 */
 
1206
int up_interface(const struct dirent *if_entry){
 
1207
  if(if_entry->d_name[0] == '.'){
 
1208
    return 0;
 
1209
  }
 
1210
  
 
1211
  struct ifreq ifr;
 
1212
  if(not get_flags(if_entry->d_name, &ifr)){
 
1213
    if(debug){
 
1214
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1215
                   "\"%s\"\n", if_entry->d_name);
 
1216
    }
 
1217
    return 0;
 
1218
  }
 
1219
  
 
1220
  /* Reject down interfaces */
 
1221
  if(not (ifr.ifr_flags & IFF_UP)){
 
1222
    if(debug){
 
1223
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1224
                   if_entry->d_name);
 
1225
    }
 
1226
    return 0;
 
1227
  }
 
1228
  
 
1229
  /* Reject non-running interfaces */
 
1230
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1231
    if(debug){
 
1232
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1233
                   if_entry->d_name);
 
1234
    }
 
1235
    return 0;
 
1236
  }
 
1237
  
 
1238
  if(not good_flags(if_entry->d_name, &ifr)){
 
1239
    return 0;
1189
1240
  }
1190
1241
  return 1;
1191
1242
}
1201
1252
  return 1;
1202
1253
}
1203
1254
 
 
1255
/* Is this directory entry a runnable program? */
 
1256
int runnable_hook(const struct dirent *direntry){
 
1257
  int ret;
 
1258
  size_t sret;
 
1259
  struct stat st;
 
1260
  
 
1261
  if((direntry->d_name)[0] == '\0'){
 
1262
    /* Empty name? */
 
1263
    return 0;
 
1264
  }
 
1265
  
 
1266
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1267
                "abcdefghijklmnopqrstuvwxyz"
 
1268
                "0123456789"
 
1269
                "_-");
 
1270
  if((direntry->d_name)[sret] != '\0'){
 
1271
    /* Contains non-allowed characters */
 
1272
    if(debug){
 
1273
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1274
                   direntry->d_name);
 
1275
    }
 
1276
    return 0;
 
1277
  }
 
1278
  
 
1279
  char *fullname = NULL;
 
1280
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1281
  if(ret < 0){
 
1282
    perror_plus("asprintf");
 
1283
    return 0;
 
1284
  }
 
1285
  
 
1286
  ret = stat(fullname, &st);
 
1287
  if(ret == -1){
 
1288
    if(debug){
 
1289
      perror_plus("Could not stat hook");
 
1290
    }
 
1291
    return 0;
 
1292
  }
 
1293
  if(not (S_ISREG(st.st_mode))){
 
1294
    /* Not a regular file */
 
1295
    if(debug){
 
1296
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1297
                   direntry->d_name);
 
1298
    }
 
1299
    return 0;
 
1300
  }
 
1301
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1302
    /* Not executable */
 
1303
    if(debug){
 
1304
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1305
                   direntry->d_name);
 
1306
    }
 
1307
    return 0;
 
1308
  }
 
1309
  if(debug){
 
1310
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1311
                 direntry->d_name);
 
1312
  }
 
1313
  return 1;
 
1314
}
 
1315
 
1204
1316
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1205
1317
  int ret;
1206
1318
  struct timespec now;
1210
1322
  while(true){
1211
1323
    if(mc.current_server == NULL){
1212
1324
      if (debug){
1213
 
        fprintf(stderr,
1214
 
                "Wait until first server is found. No timeout!\n");
 
1325
        fprintf_plus(stderr, "Wait until first server is found."
 
1326
                     " No timeout!\n");
1215
1327
      }
1216
1328
      ret = avahi_simple_poll_iterate(s, -1);
1217
1329
    } else {
1218
1330
      if (debug){
1219
 
        fprintf(stderr, "Check current_server if we should run it,"
1220
 
                " or wait\n");
 
1331
        fprintf_plus(stderr, "Check current_server if we should run"
 
1332
                     " it, or wait\n");
1221
1333
      }
1222
1334
      /* the current time */
1223
1335
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1239
1351
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1240
1352
      
1241
1353
      if (debug){
1242
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1354
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1355
                     block_time);
1243
1356
      }
1244
1357
      
1245
1358
      if(block_time <= 0){
1265
1378
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1266
1379
    }
1267
1380
    if(ret != 0){
1268
 
      if (ret > 0 or errno != EINTR) {
 
1381
      if (ret > 0 or errno != EINTR){
1269
1382
        return (ret != 1) ? ret : 0;
1270
1383
      }
1271
1384
    }
1272
1385
  }
1273
1386
}
1274
1387
 
 
1388
bool run_network_hooks(const char *mode, const char *interface,
 
1389
                       const float delay){
 
1390
  struct dirent **direntries;
 
1391
  struct dirent *direntry;
 
1392
  int ret;
 
1393
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1394
                         alphasort);
 
1395
  if(numhooks == -1){
 
1396
    perror_plus("scandir");
 
1397
  } else {
 
1398
    int devnull = open("/dev/null", O_RDONLY);
 
1399
    for(int i = 0; i < numhooks; i++){
 
1400
      direntry = direntries[i];
 
1401
      char *fullname = NULL;
 
1402
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1403
      if(ret < 0){
 
1404
        perror_plus("asprintf");
 
1405
        continue;
 
1406
      }
 
1407
      if(debug){
 
1408
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1409
                     direntry->d_name);
 
1410
      }
 
1411
      pid_t hook_pid = fork();
 
1412
      if(hook_pid == 0){
 
1413
        /* Child */
 
1414
        /* Raise privileges */
 
1415
        errno = 0;
 
1416
        ret = seteuid(0);
 
1417
        if(ret == -1){
 
1418
          perror_plus("seteuid");
 
1419
        }
 
1420
        /* Raise privileges even more */
 
1421
        errno = 0;
 
1422
        ret = setuid(0);
 
1423
        if(ret == -1){
 
1424
          perror_plus("setuid");
 
1425
        }
 
1426
        /* Set group */
 
1427
        errno = 0;
 
1428
        ret = setgid(0);
 
1429
        if(ret == -1){
 
1430
          perror_plus("setgid");
 
1431
        }
 
1432
        /* Reset supplementary groups */
 
1433
        errno = 0;
 
1434
        ret = setgroups(0, NULL);
 
1435
        if(ret == -1){
 
1436
          perror_plus("setgroups");
 
1437
        }
 
1438
        dup2(devnull, STDIN_FILENO);
 
1439
        close(devnull);
 
1440
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1441
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1442
        if(ret == -1){
 
1443
          perror_plus("setenv");
 
1444
          _exit(EX_OSERR);
 
1445
        }
 
1446
        ret = setenv("DEVICE", interface, 1);
 
1447
        if(ret == -1){
 
1448
          perror_plus("setenv");
 
1449
          _exit(EX_OSERR);
 
1450
        }
 
1451
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1452
        if(ret == -1){
 
1453
          perror_plus("setenv");
 
1454
          _exit(EX_OSERR);
 
1455
        }
 
1456
        ret = setenv("MODE", mode, 1);
 
1457
        if(ret == -1){
 
1458
          perror_plus("setenv");
 
1459
          _exit(EX_OSERR);
 
1460
        }
 
1461
        char *delaystring;
 
1462
        ret = asprintf(&delaystring, "%f", delay);
 
1463
        if(ret == -1){
 
1464
          perror_plus("asprintf");
 
1465
          _exit(EX_OSERR);
 
1466
        }
 
1467
        ret = setenv("DELAY", delaystring, 1);
 
1468
        if(ret == -1){
 
1469
          free(delaystring);
 
1470
          perror_plus("setenv");
 
1471
          _exit(EX_OSERR);
 
1472
        }
 
1473
        free(delaystring);
 
1474
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1475
          perror_plus("execl");
 
1476
          _exit(EXIT_FAILURE);
 
1477
        }
 
1478
      } else {
 
1479
        int status;
 
1480
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1481
          perror_plus("waitpid");
 
1482
          free(fullname);
 
1483
          continue;
 
1484
        }
 
1485
        if(WIFEXITED(status)){
 
1486
          if(WEXITSTATUS(status) != 0){
 
1487
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1488
                         " with status %d\n", direntry->d_name,
 
1489
                         WEXITSTATUS(status));
 
1490
            free(fullname);
 
1491
            continue;
 
1492
          }
 
1493
        } else if(WIFSIGNALED(status)){
 
1494
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1495
                       " signal %d\n", direntry->d_name,
 
1496
                       WTERMSIG(status));
 
1497
          free(fullname);
 
1498
          continue;
 
1499
        } else {
 
1500
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1501
                       " crashed\n", direntry->d_name);
 
1502
          free(fullname);
 
1503
          continue;
 
1504
        }
 
1505
      }
 
1506
      free(fullname);
 
1507
      if(debug){
 
1508
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1509
                     direntry->d_name);
 
1510
      }
 
1511
    }
 
1512
    close(devnull);
 
1513
  }
 
1514
  return true;
 
1515
}
 
1516
 
1275
1517
int main(int argc, char *argv[]){
1276
1518
  AvahiSServiceBrowser *sb = NULL;
1277
1519
  int error;
1359
1601
        .arg = "SECONDS",
1360
1602
        .doc = "Retry interval used when denied by the mandos server",
1361
1603
        .group = 2 },
 
1604
      { .name = "network-hook-dir", .key = 133,
 
1605
        .arg = "DIR",
 
1606
        .doc = "Directory where network hooks are located",
 
1607
        .group = 2 },
1362
1608
      /*
1363
1609
       * These reproduce what we would get without ARGP_NO_HELP
1364
1610
       */
1417
1663
          argp_error(state, "Bad retry interval");
1418
1664
        }
1419
1665
        break;
 
1666
      case 133:                 /* --network-hook-dir */
 
1667
        hookdir = arg;
 
1668
        break;
1420
1669
        /*
1421
1670
         * These reproduce what we would get without ARGP_NO_HELP
1422
1671
         */
1428
1677
        argp_state_help(state, state->out_stream,
1429
1678
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1430
1679
      case 'V':                 /* --version */
1431
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1680
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1432
1681
        exit(argp_err_exit_status);
1433
1682
        break;
1434
1683
      default:
1461
1710
  {
1462
1711
    /* Work around Debian bug #633582:
1463
1712
       <http://bugs.debian.org/633582> */
1464
 
    struct stat st;
1465
1713
    
1466
1714
    /* Re-raise priviliges */
1467
1715
    errno = 0;
1468
1716
    ret = seteuid(0);
1469
1717
    if(ret == -1){
1470
1718
      perror_plus("seteuid");
1471
 
    }
1472
 
    
1473
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1474
 
      int seckey_fd = open(seckey, O_RDONLY);
1475
 
      if(seckey_fd == -1){
1476
 
        perror_plus("open");
1477
 
      } else {
1478
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1479
 
        if(ret == -1){
1480
 
          perror_plus("fstat");
1481
 
        } else {
1482
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1483
 
            ret = fchown(seckey_fd, uid, gid);
1484
 
            if(ret == -1){
1485
 
              perror_plus("fchown");
1486
 
            }
1487
 
          }
1488
 
        }
1489
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1490
 
      }
1491
 
    }
1492
 
    
1493
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1494
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1495
 
      if(pubkey_fd == -1){
1496
 
        perror_plus("open");
1497
 
      } else {
1498
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1499
 
        if(ret == -1){
1500
 
          perror_plus("fstat");
1501
 
        } else {
1502
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1503
 
            ret = fchown(pubkey_fd, uid, gid);
1504
 
            if(ret == -1){
1505
 
              perror_plus("fchown");
1506
 
            }
1507
 
          }
1508
 
        }
1509
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1510
 
      }
1511
 
    }
1512
 
    
1513
 
    /* Lower privileges */
1514
 
    errno = 0;
1515
 
    ret = seteuid(uid);
1516
 
    if(ret == -1){
1517
 
      perror_plus("seteuid");
1518
 
    }
 
1719
    } else {
 
1720
      struct stat st;
 
1721
      
 
1722
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1723
        int seckey_fd = open(seckey, O_RDONLY);
 
1724
        if(seckey_fd == -1){
 
1725
          perror_plus("open");
 
1726
        } else {
 
1727
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1728
          if(ret == -1){
 
1729
            perror_plus("fstat");
 
1730
          } else {
 
1731
            if(S_ISREG(st.st_mode)
 
1732
               and st.st_uid == 0 and st.st_gid == 0){
 
1733
              ret = fchown(seckey_fd, uid, gid);
 
1734
              if(ret == -1){
 
1735
                perror_plus("fchown");
 
1736
              }
 
1737
            }
 
1738
          }
 
1739
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1740
        }
 
1741
      }
 
1742
    
 
1743
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1744
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1745
        if(pubkey_fd == -1){
 
1746
          perror_plus("open");
 
1747
        } else {
 
1748
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1749
          if(ret == -1){
 
1750
            perror_plus("fstat");
 
1751
          } else {
 
1752
            if(S_ISREG(st.st_mode)
 
1753
               and st.st_uid == 0 and st.st_gid == 0){
 
1754
              ret = fchown(pubkey_fd, uid, gid);
 
1755
              if(ret == -1){
 
1756
                perror_plus("fchown");
 
1757
              }
 
1758
            }
 
1759
          }
 
1760
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1761
        }
 
1762
      }
 
1763
    
 
1764
      /* Lower privileges */
 
1765
      errno = 0;
 
1766
      ret = seteuid(uid);
 
1767
      if(ret == -1){
 
1768
        perror_plus("seteuid");
 
1769
      }
 
1770
    }
 
1771
  }
 
1772
  
 
1773
  /* Run network hooks */
 
1774
  if(not run_network_hooks("start", interface, delay)){
 
1775
    goto end;
1519
1776
  }
1520
1777
  
1521
1778
  if(not debug){
1522
1779
    avahi_set_log_function(empty_log);
1523
1780
  }
1524
 
 
 
1781
  
1525
1782
  if(interface[0] == '\0'){
1526
1783
    struct dirent **direntries;
1527
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1784
    /* First look for interfaces that are up */
 
1785
    ret = scandir(sys_class_net, &direntries, up_interface,
1528
1786
                  alphasort);
 
1787
    if(ret == 0){
 
1788
      /* No up interfaces, look for any good interfaces */
 
1789
      free(direntries);
 
1790
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1791
                    alphasort);
 
1792
    }
1529
1793
    if(ret >= 1){
1530
 
      /* Pick the first good interface */
 
1794
      /* Pick the first interface returned */
1531
1795
      interface = strdup(direntries[0]->d_name);
1532
1796
      if(debug){
1533
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1797
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1534
1798
      }
1535
1799
      if(interface == NULL){
1536
1800
        perror_plus("malloc");
1541
1805
      free(direntries);
1542
1806
    } else {
1543
1807
      free(direntries);
1544
 
      fprintf(stderr, "Could not find a network interface\n");
 
1808
      fprintf_plus(stderr, "Could not find a network interface\n");
1545
1809
      exitcode = EXIT_FAILURE;
1546
1810
      goto end;
1547
1811
    }
1553
1817
  srand((unsigned int) time(NULL));
1554
1818
  mc.simple_poll = avahi_simple_poll_new();
1555
1819
  if(mc.simple_poll == NULL){
1556
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1820
    fprintf_plus(stderr,
 
1821
                 "Avahi: Failed to create simple poll object.\n");
1557
1822
    exitcode = EX_UNAVAILABLE;
1558
1823
    goto end;
1559
1824
  }
1625
1890
  if(strcmp(interface, "none") != 0){
1626
1891
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1627
1892
    if(if_index == 0){
1628
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1893
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1629
1894
      exitcode = EX_UNAVAILABLE;
1630
1895
      goto end;
1631
1896
    }
1751
2016
#endif  /* __linux__ */
1752
2017
    /* Lower privileges */
1753
2018
    errno = 0;
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
 
      }
 
2019
    /* Lower privileges */
 
2020
    ret = seteuid(uid);
 
2021
    if(ret == -1){
 
2022
      perror_plus("seteuid");
1766
2023
    }
1767
2024
  }
1768
2025
  
1772
2029
  
1773
2030
  ret = init_gnutls_global(pubkey, seckey);
1774
2031
  if(ret == -1){
1775
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2032
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1776
2033
    exitcode = EX_UNAVAILABLE;
1777
2034
    goto end;
1778
2035
  } else {
1794
2051
  }
1795
2052
  
1796
2053
  if(not init_gpgme(pubkey, seckey, tempdir)){
1797
 
    fprintf(stderr, "init_gpgme failed\n");
 
2054
    fprintf_plus(stderr, "init_gpgme failed\n");
1798
2055
    exitcode = EX_UNAVAILABLE;
1799
2056
    goto end;
1800
2057
  } else {
1810
2067
    /* (Mainly meant for debugging) */
1811
2068
    char *address = strrchr(connect_to, ':');
1812
2069
    if(address == NULL){
1813
 
      fprintf(stderr, "No colon in address\n");
 
2070
      fprintf_plus(stderr, "No colon in address\n");
1814
2071
      exitcode = EX_USAGE;
1815
2072
      goto end;
1816
2073
    }
1824
2081
    tmpmax = strtoimax(address+1, &tmp, 10);
1825
2082
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1826
2083
       or tmpmax != (uint16_t)tmpmax){
1827
 
      fprintf(stderr, "Bad port number\n");
 
2084
      fprintf_plus(stderr, "Bad port number\n");
1828
2085
      exitcode = EX_USAGE;
1829
2086
      goto end;
1830
2087
    }
1860
2117
        break;
1861
2118
      }
1862
2119
      if(debug){
1863
 
        fprintf(stderr, "Retrying in %d seconds\n",
1864
 
                (int)retry_interval);
 
2120
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2121
                     (int)retry_interval);
1865
2122
      }
1866
2123
      sleep((int)retry_interval);
1867
2124
    }
1869
2126
    if (not quit_now){
1870
2127
      exitcode = EXIT_SUCCESS;
1871
2128
    }
1872
 
 
 
2129
    
1873
2130
    goto end;
1874
2131
  }
1875
2132
  
1897
2154
  
1898
2155
  /* Check if creating the Avahi server object succeeded */
1899
2156
  if(mc.server == NULL){
1900
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1901
 
            avahi_strerror(error));
 
2157
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2158
                 avahi_strerror(error));
1902
2159
    exitcode = EX_UNAVAILABLE;
1903
2160
    goto end;
1904
2161
  }
1912
2169
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1913
2170
                                   NULL, 0, browse_callback, NULL);
1914
2171
  if(sb == NULL){
1915
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1916
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2172
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2173
                 avahi_strerror(avahi_server_errno(mc.server)));
1917
2174
    exitcode = EX_UNAVAILABLE;
1918
2175
    goto end;
1919
2176
  }
1925
2182
  /* Run the main loop */
1926
2183
  
1927
2184
  if(debug){
1928
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2185
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1929
2186
  }
1930
2187
 
1931
2188
  ret = avahi_loop_with_timeout(mc.simple_poll,
1932
2189
                                (int)(retry_interval * 1000));
1933
2190
  if(debug){
1934
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1935
 
            (ret == 0) ? "successfully" : "with error");
 
2191
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2192
                 (ret == 0) ? "successfully" : "with error");
1936
2193
  }
1937
2194
  
1938
2195
 end:
1939
2196
  
1940
2197
  if(debug){
1941
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2198
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1942
2199
  }
1943
2200
  
1944
2201
  /* Cleanup things */
1960
2217
  if(gpgme_initialized){
1961
2218
    gpgme_release(mc.ctx);
1962
2219
  }
1963
 
 
 
2220
  
1964
2221
  /* Cleans up the circular linked list of Mandos servers the client
1965
2222
     has seen */
1966
2223
  if(mc.current_server != NULL){
1972
2229
    }
1973
2230
  }
1974
2231
  
1975
 
  /* Take down the network interface */
1976
 
  if(take_down_interface){
1977
 
    /* Re-raise priviliges */
 
2232
  /* Run network hooks */
 
2233
  run_network_hooks("stop", interface, delay);
 
2234
  
 
2235
  /* Re-raise priviliges */
 
2236
  {
1978
2237
    errno = 0;
1979
2238
    ret = seteuid(0);
1980
2239
    if(ret == -1){
1981
2240
      perror_plus("seteuid");
1982
2241
    }
1983
 
    if(geteuid() == 0){
 
2242
    
 
2243
    /* Take down the network interface */
 
2244
    if(take_down_interface and geteuid() == 0){
1984
2245
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1985
2246
      if(ret == -1){
1986
2247
        perror_plus("ioctl SIOCGIFFLAGS");
1987
 
      } else if(network.ifr_flags & IFF_UP) {
 
2248
      } else if(network.ifr_flags & IFF_UP){
1988
2249
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1989
2250
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1990
2251
        if(ret == -1){
1995
2256
      if(ret == -1){
1996
2257
        perror_plus("close");
1997
2258
      }
1998
 
      /* Lower privileges permanently */
1999
 
      errno = 0;
2000
 
      ret = setuid(uid);
2001
 
      if(ret == -1){
2002
 
        perror_plus("setuid");
2003
 
      }
2004
2259
    }
2005
2260
  }
 
2261
  /* Lower privileges permanently */
 
2262
  errno = 0;
 
2263
  ret = setuid(uid);
 
2264
  if(ret == -1){
 
2265
    perror_plus("setuid");
 
2266
  }
2006
2267
  
2007
2268
  /* Removes the GPGME temp directory and all files inside */
2008
2269
  if(tempdir_created){
2022
2283
        }
2023
2284
        ret = remove(fullname);
2024
2285
        if(ret == -1){
2025
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2026
 
                  strerror(errno));
 
2286
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2287
                       strerror(errno));
2027
2288
        }
2028
2289
        free(fullname);
2029
2290
      }