/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 Hogeborn
  • Date: 2012-01-01 20:45:53 UTC
  • Revision ID: teddy@recompile.se-20120101204553-f1zlty873gswtf5n
* README: Hint that the intro(8mandos) manual page is in the server
          package.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
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
131
134
const char *argp_program_bug_address = "<mandos@recompile.se>";
132
135
static const char sys_class_net[] = "/sys/class/net";
133
136
char *connect_to = NULL;
 
137
const char *hookdir = HOOKDIR;
134
138
 
135
139
/* Doubly linked list that need to be circularly linked when used */
136
140
typedef struct server{
166
170
 
167
171
/* Function to use when printing errors */
168
172
void perror_plus(const char *print_text){
 
173
  int e = errno;
169
174
  fprintf(stderr, "Mandos plugin %s: ",
170
175
          program_invocation_short_name);
 
176
  errno = e;
171
177
  perror(print_text);
172
178
}
173
179
 
 
180
__attribute__((format (gnu_printf, 2, 3)))
 
181
int fprintf_plus(FILE *stream, const char *format, ...){
 
182
  va_list ap;
 
183
  va_start (ap, format);
 
184
  
 
185
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
186
                             program_invocation_short_name));
 
187
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
188
}
 
189
 
174
190
/*
175
191
 * Make additional room in "buffer" for at least BUFFER_SIZE more
176
192
 * bytes. "buffer_capacity" is how much is currently allocated,
177
193
 * "buffer_length" is how much is already used.
178
194
 */
179
195
size_t incbuffer(char **buffer, size_t buffer_length,
180
 
                  size_t buffer_capacity){
 
196
                 size_t buffer_capacity){
181
197
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
182
198
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
183
199
    if(buffer == NULL){
189
205
}
190
206
 
191
207
/* Add server to set of servers to retry periodically */
192
 
int add_server(const char *ip, uint16_t port,
193
 
                 AvahiIfIndex if_index,
194
 
                 int af){
 
208
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
209
                int af){
195
210
  int ret;
196
211
  server *new_server = malloc(sizeof(server));
197
212
  if(new_server == NULL){
198
213
    perror_plus("malloc");
199
 
    return -1;
 
214
    return false;
200
215
  }
201
216
  *new_server = (server){ .ip = strdup(ip),
202
 
                         .port = port,
203
 
                         .if_index = if_index,
204
 
                         .af = af };
 
217
                          .port = port,
 
218
                          .if_index = if_index,
 
219
                          .af = af };
205
220
  if(new_server->ip == NULL){
206
221
    perror_plus("strdup");
207
 
    return -1;
 
222
    return false;
208
223
  }
209
224
  /* Special case of first server */
210
225
  if (mc.current_server == NULL){
221
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
222
237
  if(ret == -1){
223
238
    perror_plus("clock_gettime");
224
 
    return -1;
 
239
    return false;
225
240
  }
226
 
  return 0;
 
241
  return true;
227
242
}
228
243
 
229
244
/* 
230
245
 * Initialize GPGME.
231
246
 */
232
 
static bool init_gpgme(const char *seckey,
233
 
                       const char *pubkey, const char *tempdir){
 
247
static bool init_gpgme(const char *seckey, const char *pubkey,
 
248
                       const char *tempdir){
234
249
  gpgme_error_t rc;
235
250
  gpgme_engine_info_t engine_info;
236
251
  
251
266
    
252
267
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
253
268
    if(rc != GPG_ERR_NO_ERROR){
254
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
255
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
269
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
270
                   gpgme_strsource(rc), gpgme_strerror(rc));
256
271
      return false;
257
272
    }
258
273
    
259
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
260
275
    if(rc != GPG_ERR_NO_ERROR){
261
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
262
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
263
278
      return false;
264
279
    }
265
280
    
272
287
  }
273
288
  
274
289
  if(debug){
275
 
    fprintf(stderr, "Initializing GPGME\n");
 
290
    fprintf_plus(stderr, "Initializing GPGME\n");
276
291
  }
277
292
  
278
293
  /* Init GPGME */
279
294
  gpgme_check_version(NULL);
280
295
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
281
296
  if(rc != GPG_ERR_NO_ERROR){
282
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
283
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
297
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
298
                 gpgme_strsource(rc), gpgme_strerror(rc));
284
299
    return false;
285
300
  }
286
301
  
287
302
  /* Set GPGME home directory for the OpenPGP engine only */
288
303
  rc = gpgme_get_engine_info(&engine_info);
289
304
  if(rc != GPG_ERR_NO_ERROR){
290
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
291
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
305
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
306
                 gpgme_strsource(rc), gpgme_strerror(rc));
292
307
    return false;
293
308
  }
294
309
  while(engine_info != NULL){
300
315
    engine_info = engine_info->next;
301
316
  }
302
317
  if(engine_info == NULL){
303
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
318
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
319
                 tempdir);
304
320
    return false;
305
321
  }
306
322
  
307
323
  /* Create new GPGME "context" */
308
324
  rc = gpgme_new(&(mc.ctx));
309
325
  if(rc != GPG_ERR_NO_ERROR){
310
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
311
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
328
                 gpgme_strerror(rc));
312
329
    return false;
313
330
  }
314
331
  
333
350
  ssize_t plaintext_length = 0;
334
351
  
335
352
  if(debug){
336
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
353
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
337
354
  }
338
355
  
339
356
  /* Create new GPGME data buffer from memory cryptotext */
340
357
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
341
358
                               0);
342
359
  if(rc != GPG_ERR_NO_ERROR){
343
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
344
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
360
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
361
                 gpgme_strsource(rc), gpgme_strerror(rc));
345
362
    return -1;
346
363
  }
347
364
  
348
365
  /* Create new empty GPGME data buffer for the plaintext */
349
366
  rc = gpgme_data_new(&dh_plain);
350
367
  if(rc != GPG_ERR_NO_ERROR){
351
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
352
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
368
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
369
                 "bad gpgme_data_new: %s: %s\n",
 
370
                 gpgme_strsource(rc), gpgme_strerror(rc));
353
371
    gpgme_data_release(dh_crypto);
354
372
    return -1;
355
373
  }
358
376
     data buffer */
359
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
360
378
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
362
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
363
381
    plaintext_length = -1;
364
382
    if(debug){
365
383
      gpgme_decrypt_result_t result;
366
384
      result = gpgme_op_decrypt_result(mc.ctx);
367
385
      if(result == NULL){
368
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
369
387
      } else {
370
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
371
 
                result->unsupported_algorithm);
372
 
        fprintf(stderr, "Wrong key usage: %u\n",
373
 
                result->wrong_key_usage);
 
388
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
389
                     result->unsupported_algorithm);
 
390
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
391
                     result->wrong_key_usage);
374
392
        if(result->file_name != NULL){
375
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
393
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
376
394
        }
377
395
        gpgme_recipient_t recipient;
378
396
        recipient = result->recipients;
379
397
        while(recipient != NULL){
380
 
          fprintf(stderr, "Public key algorithm: %s\n",
381
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
382
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
383
 
          fprintf(stderr, "Secret key available: %s\n",
384
 
                  recipient->status == GPG_ERR_NO_SECKEY
385
 
                  ? "No" : "Yes");
 
398
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
399
                       gpgme_pubkey_algo_name
 
400
                       (recipient->pubkey_algo));
 
401
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
402
          fprintf_plus(stderr, "Secret key available: %s\n",
 
403
                       recipient->status == GPG_ERR_NO_SECKEY
 
404
                       ? "No" : "Yes");
386
405
          recipient = recipient->next;
387
406
        }
388
407
      }
391
410
  }
392
411
  
393
412
  if(debug){
394
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
413
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
395
414
  }
396
415
  
397
416
  /* Seek back to the beginning of the GPGME plaintext data buffer */
404
423
  *plaintext = NULL;
405
424
  while(true){
406
425
    plaintext_capacity = incbuffer(plaintext,
407
 
                                      (size_t)plaintext_length,
408
 
                                      plaintext_capacity);
 
426
                                   (size_t)plaintext_length,
 
427
                                   plaintext_capacity);
409
428
    if(plaintext_capacity == 0){
410
 
        perror_plus("incbuffer");
411
 
        plaintext_length = -1;
412
 
        goto decrypt_end;
 
429
      perror_plus("incbuffer");
 
430
      plaintext_length = -1;
 
431
      goto decrypt_end;
413
432
    }
414
433
    
415
434
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
428
447
  }
429
448
  
430
449
  if(debug){
431
 
    fprintf(stderr, "Decrypted password is: ");
 
450
    fprintf_plus(stderr, "Decrypted password is: ");
432
451
    for(ssize_t i = 0; i < plaintext_length; i++){
433
452
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
434
453
    }
456
475
/* GnuTLS log function callback */
457
476
static void debuggnutls(__attribute__((unused)) int level,
458
477
                        const char* string){
459
 
  fprintf(stderr, "GnuTLS: %s", string);
 
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
460
479
}
461
480
 
462
481
static int init_gnutls_global(const char *pubkeyfilename,
464
483
  int ret;
465
484
  
466
485
  if(debug){
467
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
486
    fprintf_plus(stderr, "Initializing GnuTLS\n");
468
487
  }
469
488
  
470
489
  ret = gnutls_global_init();
471
490
  if(ret != GNUTLS_E_SUCCESS){
472
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
473
 
            safer_gnutls_strerror(ret));
 
491
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
492
                 safer_gnutls_strerror(ret));
474
493
    return -1;
475
494
  }
476
495
  
485
504
  /* OpenPGP credentials */
486
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
487
506
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
489
 
            safer_gnutls_strerror(ret));
 
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
508
                 safer_gnutls_strerror(ret));
490
509
    gnutls_global_deinit();
491
510
    return -1;
492
511
  }
493
512
  
494
513
  if(debug){
495
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
496
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
497
 
            seckeyfilename);
 
514
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
515
                 " secret key %s as GnuTLS credentials\n",
 
516
                 pubkeyfilename,
 
517
                 seckeyfilename);
498
518
  }
499
519
  
500
520
  ret = gnutls_certificate_set_openpgp_key_file
501
521
    (mc.cred, pubkeyfilename, seckeyfilename,
502
522
     GNUTLS_OPENPGP_FMT_BASE64);
503
523
  if(ret != GNUTLS_E_SUCCESS){
504
 
    fprintf(stderr,
505
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
506
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
507
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
508
 
            safer_gnutls_strerror(ret));
 
524
    fprintf_plus(stderr,
 
525
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
526
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
527
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
528
                 safer_gnutls_strerror(ret));
509
529
    goto globalfail;
510
530
  }
511
531
  
512
532
  /* GnuTLS server initialization */
513
533
  ret = gnutls_dh_params_init(&mc.dh_params);
514
534
  if(ret != GNUTLS_E_SUCCESS){
515
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
516
 
            " %s\n", safer_gnutls_strerror(ret));
 
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
536
                 " initialization: %s\n",
 
537
                 safer_gnutls_strerror(ret));
517
538
    goto globalfail;
518
539
  }
519
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
520
541
  if(ret != GNUTLS_E_SUCCESS){
521
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
522
 
            safer_gnutls_strerror(ret));
 
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
543
                 safer_gnutls_strerror(ret));
523
544
    goto globalfail;
524
545
  }
525
546
  
545
566
    }
546
567
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
547
568
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
569
    fprintf_plus(stderr,
 
570
                 "Error in GnuTLS session initialization: %s\n",
 
571
                 safer_gnutls_strerror(ret));
550
572
  }
551
573
  
552
574
  {
559
581
      }
560
582
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
561
583
    if(ret != GNUTLS_E_SUCCESS){
562
 
      fprintf(stderr, "Syntax error at: %s\n", err);
563
 
      fprintf(stderr, "GnuTLS error: %s\n",
564
 
              safer_gnutls_strerror(ret));
 
584
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
585
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
586
                   safer_gnutls_strerror(ret));
565
587
      gnutls_deinit(*session);
566
588
      return -1;
567
589
    }
576
598
    }
577
599
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
578
600
  if(ret != GNUTLS_E_SUCCESS){
579
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
580
 
            safer_gnutls_strerror(ret));
 
601
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
602
                 safer_gnutls_strerror(ret));
581
603
    gnutls_deinit(*session);
582
604
    return -1;
583
605
  }
628
650
    pf = PF_INET;
629
651
    break;
630
652
  default:
631
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
653
    fprintf_plus(stderr, "Bad address family: %d\n", af);
632
654
    errno = EINVAL;
633
655
    return -1;
634
656
  }
639
661
  }
640
662
  
641
663
  if(debug){
642
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
643
 
            "\n", ip, port);
 
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
665
                 PRIu16 "\n", ip, port);
644
666
  }
645
667
  
646
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
672
694
  }
673
695
  if(ret == 0){
674
696
    int e = errno;
675
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
697
    fprintf_plus(stderr, "Bad address: %s\n", ip);
676
698
    errno = e;
677
699
    goto mandos_end;
678
700
  }
683
705
    
684
706
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
685
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
686
 
                              -Wunreachable-code*/
 
708
                                -Wunreachable-code*/
687
709
      if(if_index == AVAHI_IF_UNSPEC){
688
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
689
 
                " without a network interface\n");
 
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
711
                     " incomplete without a network interface\n");
690
712
        errno = EINVAL;
691
713
        goto mandos_end;
692
714
      }
710
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
733
        perror_plus("if_indextoname");
712
734
      } else {
713
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
 
                ip, interface, port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
715
737
      }
716
738
    } else {
717
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
718
 
              port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
719
741
    }
720
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
721
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
731
753
      perror_plus("inet_ntop");
732
754
    } else {
733
755
      if(strcmp(addrstr, ip) != 0){
734
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
735
757
      }
736
758
    }
737
759
  }
765
787
  while(true){
766
788
    size_t out_size = strlen(out);
767
789
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
 
                                   out_size - written));
 
790
                                        out_size - written));
769
791
    if(ret == -1){
770
792
      int e = errno;
771
793
      perror_plus("write");
791
813
  }
792
814
  
793
815
  if(debug){
794
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
816
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
795
817
  }
796
818
  
797
819
  if(quit_now){
817
839
  
818
840
  if(ret != GNUTLS_E_SUCCESS){
819
841
    if(debug){
820
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
842
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
821
843
      gnutls_perror(ret);
822
844
    }
823
845
    errno = EPROTO;
827
849
  /* Read OpenPGP packet that contains the wanted password */
828
850
  
829
851
  if(debug){
830
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
831
 
            ip);
 
852
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
853
                 " %s\n", ip);
832
854
  }
833
855
  
834
856
  while(true){
839
861
    }
840
862
    
841
863
    buffer_capacity = incbuffer(&buffer, buffer_length,
842
 
                                   buffer_capacity);
 
864
                                buffer_capacity);
843
865
    if(buffer_capacity == 0){
844
866
      int e = errno;
845
867
      perror_plus("incbuffer");
872
894
          }
873
895
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
874
896
        if(ret < 0){
875
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
897
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
898
                       "***\n");
876
899
          gnutls_perror(ret);
877
900
          errno = EPROTO;
878
901
          goto mandos_end;
879
902
        }
880
903
        break;
881
904
      default:
882
 
        fprintf(stderr, "Unknown error while reading data from"
883
 
                " encrypted session with Mandos server\n");
 
905
        fprintf_plus(stderr, "Unknown error while reading data from"
 
906
                     " encrypted session with Mandos server\n");
884
907
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
885
908
        errno = EIO;
886
909
        goto mandos_end;
891
914
  }
892
915
  
893
916
  if(debug){
894
 
    fprintf(stderr, "Closing TLS session\n");
 
917
    fprintf_plus(stderr, "Closing TLS session\n");
895
918
  }
896
919
  
897
920
  if(quit_now){
909
932
  
910
933
  if(buffer_length > 0){
911
934
    ssize_t decrypted_buffer_size;
912
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
913
 
                                               buffer_length,
 
935
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
914
936
                                               &decrypted_buffer);
915
937
    if(decrypted_buffer_size >= 0){
916
938
      
927
949
        if(ret == 0 and ferror(stdout)){
928
950
          int e = errno;
929
951
          if(debug){
930
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
931
 
                    strerror(errno));
 
952
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
953
                         strerror(errno));
932
954
          }
933
955
          errno = e;
934
956
          goto mandos_end;
991
1013
  switch(event){
992
1014
  default:
993
1015
  case AVAHI_RESOLVER_FAILURE:
994
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
995
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
996
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1016
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1017
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1018
                 domain,
 
1019
                 avahi_strerror(avahi_server_errno(mc.server)));
997
1020
    break;
998
1021
    
999
1022
  case AVAHI_RESOLVER_FOUND:
1001
1024
      char ip[AVAHI_ADDRESS_STR_MAX];
1002
1025
      avahi_address_snprint(ip, sizeof(ip), address);
1003
1026
      if(debug){
1004
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1005
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1006
 
                ip, (intmax_t)interface, port);
 
1027
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1028
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1029
                     host_name, ip, (intmax_t)interface, port);
1007
1030
      }
1008
1031
      int ret = start_mandos_communication(ip, port, interface,
1009
1032
                                           avahi_proto_to_af(proto));
1010
1033
      if(ret == 0){
1011
1034
        avahi_simple_poll_quit(mc.simple_poll);
1012
1035
      } else {
1013
 
        ret = add_server(ip, port, interface,
1014
 
                         avahi_proto_to_af(proto));
 
1036
        if(not add_server(ip, port, interface,
 
1037
                          avahi_proto_to_af(proto))){
 
1038
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1039
                       " list\n", name);
 
1040
        }
1015
1041
      }
1016
1042
    }
1017
1043
  }
1041
1067
  default:
1042
1068
  case AVAHI_BROWSER_FAILURE:
1043
1069
    
1044
 
    fprintf(stderr, "(Avahi browser) %s\n",
1045
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1070
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1071
                 avahi_strerror(avahi_server_errno(mc.server)));
1046
1072
    avahi_simple_poll_quit(mc.simple_poll);
1047
1073
    return;
1048
1074
    
1055
1081
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1056
1082
                                    name, type, domain, protocol, 0,
1057
1083
                                    resolve_callback, NULL) == NULL)
1058
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1059
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1084
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1085
                   " %s\n", name,
 
1086
                   avahi_strerror(avahi_server_errno(mc.server)));
1060
1087
    break;
1061
1088
    
1062
1089
  case AVAHI_BROWSER_REMOVE:
1065
1092
  case AVAHI_BROWSER_ALL_FOR_NOW:
1066
1093
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1067
1094
    if(debug){
1068
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1095
      fprintf_plus(stderr, "No Mandos server found, still"
 
1096
                   " searching...\n");
1069
1097
    }
1070
1098
    break;
1071
1099
  }
1110
1138
  /* Reject the loopback device */
1111
1139
  if(ifr->ifr_flags & IFF_LOOPBACK){
1112
1140
    if(debug){
1113
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1114
 
              ifname);
 
1141
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1142
                   ifname);
1115
1143
    }
1116
1144
    return false;
1117
1145
  }
1118
1146
  /* Accept point-to-point devices only if connect_to is specified */
1119
1147
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1120
1148
    if(debug){
1121
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1122
 
              ifname);
 
1149
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1150
                   " \"%s\"\n", ifname);
1123
1151
    }
1124
1152
    return true;
1125
1153
  }
1126
1154
  /* Otherwise, reject non-broadcast-capable devices */
1127
1155
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1128
1156
    if(debug){
1129
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1130
 
              ifname);
 
1157
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1158
                   " \"%s\"\n", ifname);
1131
1159
    }
1132
1160
    return false;
1133
1161
  }
1134
1162
  /* Reject non-ARP interfaces (including dummy interfaces) */
1135
1163
  if(ifr->ifr_flags & IFF_NOARP){
1136
1164
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1165
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1166
                   ifname);
1138
1167
    }
1139
1168
    return false;
1140
1169
  }
1141
1170
  
1142
1171
  /* Accept this device */
1143
1172
  if(debug){
1144
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1173
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1145
1174
  }
1146
1175
  return true;
1147
1176
}
1159
1188
  struct ifreq ifr;
1160
1189
  if(not get_flags(if_entry->d_name, &ifr)){
1161
1190
    if(debug){
1162
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1163
 
              if_entry->d_name);
 
1191
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1192
                   "\"%s\"\n", if_entry->d_name);
1164
1193
    }
1165
1194
    return 0;
1166
1195
  }
1184
1213
  struct ifreq ifr;
1185
1214
  if(not get_flags(if_entry->d_name, &ifr)){
1186
1215
    if(debug){
1187
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1188
 
              if_entry->d_name);
 
1216
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1217
                   "\"%s\"\n", if_entry->d_name);
1189
1218
    }
1190
1219
    return 0;
1191
1220
  }
1193
1222
  /* Reject down interfaces */
1194
1223
  if(not (ifr.ifr_flags & IFF_UP)){
1195
1224
    if(debug){
1196
 
      fprintf(stderr, "Rejecting down interface \"%s\"\n",
1197
 
              if_entry->d_name);
 
1225
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1226
                   if_entry->d_name);
1198
1227
    }
1199
1228
    return 0;
1200
1229
  }
1202
1231
  /* Reject non-running interfaces */
1203
1232
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1204
1233
    if(debug){
1205
 
      fprintf(stderr, "Rejecting non-running interface \"%s\"\n",
1206
 
              if_entry->d_name);
 
1234
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1235
                   if_entry->d_name);
1207
1236
    }
1208
1237
    return 0;
1209
1238
  }
1228
1257
/* Is this directory entry a runnable program? */
1229
1258
int runnable_hook(const struct dirent *direntry){
1230
1259
  int ret;
 
1260
  size_t sret;
1231
1261
  struct stat st;
1232
1262
  
1233
1263
  if((direntry->d_name)[0] == '\0'){
1235
1265
    return 0;
1236
1266
  }
1237
1267
  
1238
 
  /* Save pointer to last character */
1239
 
  char *end = strchr(direntry->d_name, '\0')-1;
1240
 
  
1241
 
  if(*end == '~'){
1242
 
    /* Backup name~ */
1243
 
    return 0;
1244
 
  }
1245
 
  
1246
 
  if(((direntry->d_name)[0] == '#')
1247
 
     and (*end == '#')){
1248
 
    /* Temporary #name# */
1249
 
    return 0;
1250
 
  }
1251
 
  
1252
 
  /* XXX more rules here */
1253
 
  
1254
 
  ret = stat(direntry->d_name, &st);
 
1268
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1269
                "abcdefghijklmnopqrstuvwxyz"
 
1270
                "0123456789"
 
1271
                "_-");
 
1272
  if((direntry->d_name)[sret] != '\0'){
 
1273
    /* Contains non-allowed characters */
 
1274
    if(debug){
 
1275
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1276
                   direntry->d_name);
 
1277
    }
 
1278
    return 0;
 
1279
  }
 
1280
  
 
1281
  char *fullname = NULL;
 
1282
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1283
  if(ret < 0){
 
1284
    perror_plus("asprintf");
 
1285
    return 0;
 
1286
  }
 
1287
  
 
1288
  ret = stat(fullname, &st);
1255
1289
  if(ret == -1){
1256
1290
    if(debug){
1257
 
      perror_plus("Could not stat plugin");
 
1291
      perror_plus("Could not stat hook");
1258
1292
    }
1259
1293
    return 0;
1260
1294
  }
1261
1295
  if(not (S_ISREG(st.st_mode))){
1262
1296
    /* Not a regular file */
 
1297
    if(debug){
 
1298
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1299
                   direntry->d_name);
 
1300
    }
1263
1301
    return 0;
1264
1302
  }
1265
1303
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1266
1304
    /* Not executable */
 
1305
    if(debug){
 
1306
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1307
                   direntry->d_name);
 
1308
    }
1267
1309
    return 0;
1268
1310
  }
 
1311
  if(debug){
 
1312
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1313
                 direntry->d_name);
 
1314
  }
1269
1315
  return 1;
1270
1316
}
1271
1317
 
1278
1324
  while(true){
1279
1325
    if(mc.current_server == NULL){
1280
1326
      if (debug){
1281
 
        fprintf(stderr,
1282
 
                "Wait until first server is found. No timeout!\n");
 
1327
        fprintf_plus(stderr, "Wait until first server is found."
 
1328
                     " No timeout!\n");
1283
1329
      }
1284
1330
      ret = avahi_simple_poll_iterate(s, -1);
1285
1331
    } else {
1286
1332
      if (debug){
1287
 
        fprintf(stderr, "Check current_server if we should run it,"
1288
 
                " or wait\n");
 
1333
        fprintf_plus(stderr, "Check current_server if we should run"
 
1334
                     " it, or wait\n");
1289
1335
      }
1290
1336
      /* the current time */
1291
1337
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1307
1353
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1308
1354
      
1309
1355
      if (debug){
1310
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1356
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1357
                     block_time);
1311
1358
      }
1312
1359
      
1313
1360
      if(block_time <= 0){
1333
1380
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1334
1381
    }
1335
1382
    if(ret != 0){
1336
 
      if (ret > 0 or errno != EINTR) {
 
1383
      if (ret > 0 or errno != EINTR){
1337
1384
        return (ret != 1) ? ret : 0;
1338
1385
      }
1339
1386
    }
1340
1387
  }
1341
1388
}
1342
1389
 
 
1390
bool run_network_hooks(const char *mode, const char *interface,
 
1391
                       const float delay){
 
1392
  struct dirent **direntries;
 
1393
  struct dirent *direntry;
 
1394
  int ret;
 
1395
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1396
                         alphasort);
 
1397
  if(numhooks == -1){
 
1398
    perror_plus("scandir");
 
1399
  } else {
 
1400
    int devnull = open("/dev/null", O_RDONLY);
 
1401
    for(int i = 0; i < numhooks; i++){
 
1402
      direntry = direntries[i];
 
1403
      char *fullname = NULL;
 
1404
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1405
      if(ret < 0){
 
1406
        perror_plus("asprintf");
 
1407
        continue;
 
1408
      }
 
1409
      if(debug){
 
1410
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1411
                     direntry->d_name);
 
1412
      }
 
1413
      pid_t hook_pid = fork();
 
1414
      if(hook_pid == 0){
 
1415
        /* Child */
 
1416
        /* Raise privileges */
 
1417
        errno = 0;
 
1418
        ret = seteuid(0);
 
1419
        if(ret == -1){
 
1420
          perror_plus("seteuid");
 
1421
        }
 
1422
        /* Raise privileges even more */
 
1423
        errno = 0;
 
1424
        ret = setuid(0);
 
1425
        if(ret == -1){
 
1426
          perror_plus("setuid");
 
1427
        }
 
1428
        /* Set group */
 
1429
        errno = 0;
 
1430
        ret = setgid(0);
 
1431
        if(ret == -1){
 
1432
          perror_plus("setgid");
 
1433
        }
 
1434
        /* Reset supplementary groups */
 
1435
        errno = 0;
 
1436
        ret = setgroups(0, NULL);
 
1437
        if(ret == -1){
 
1438
          perror_plus("setgroups");
 
1439
        }
 
1440
        dup2(devnull, STDIN_FILENO);
 
1441
        close(devnull);
 
1442
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1443
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1444
        if(ret == -1){
 
1445
          perror_plus("setenv");
 
1446
          _exit(EX_OSERR);
 
1447
        }
 
1448
        ret = setenv("DEVICE", interface, 1);
 
1449
        if(ret == -1){
 
1450
          perror_plus("setenv");
 
1451
          _exit(EX_OSERR);
 
1452
        }
 
1453
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1454
        if(ret == -1){
 
1455
          perror_plus("setenv");
 
1456
          _exit(EX_OSERR);
 
1457
        }
 
1458
        ret = setenv("MODE", mode, 1);
 
1459
        if(ret == -1){
 
1460
          perror_plus("setenv");
 
1461
          _exit(EX_OSERR);
 
1462
        }
 
1463
        char *delaystring;
 
1464
        ret = asprintf(&delaystring, "%f", delay);
 
1465
        if(ret == -1){
 
1466
          perror_plus("asprintf");
 
1467
          _exit(EX_OSERR);
 
1468
        }
 
1469
        ret = setenv("DELAY", delaystring, 1);
 
1470
        if(ret == -1){
 
1471
          free(delaystring);
 
1472
          perror_plus("setenv");
 
1473
          _exit(EX_OSERR);
 
1474
        }
 
1475
        free(delaystring);
 
1476
        if(connect_to != NULL){
 
1477
          ret = setenv("CONNECT", connect_to, 1);
 
1478
          if(ret == -1){
 
1479
            perror_plus("setenv");
 
1480
            _exit(EX_OSERR);
 
1481
          }
 
1482
        }
 
1483
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1484
          perror_plus("execl");
 
1485
          _exit(EXIT_FAILURE);
 
1486
        }
 
1487
      } else {
 
1488
        int status;
 
1489
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1490
          perror_plus("waitpid");
 
1491
          free(fullname);
 
1492
          continue;
 
1493
        }
 
1494
        if(WIFEXITED(status)){
 
1495
          if(WEXITSTATUS(status) != 0){
 
1496
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1497
                         " with status %d\n", direntry->d_name,
 
1498
                         WEXITSTATUS(status));
 
1499
            free(fullname);
 
1500
            continue;
 
1501
          }
 
1502
        } else if(WIFSIGNALED(status)){
 
1503
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1504
                       " signal %d\n", direntry->d_name,
 
1505
                       WTERMSIG(status));
 
1506
          free(fullname);
 
1507
          continue;
 
1508
        } else {
 
1509
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1510
                       " crashed\n", direntry->d_name);
 
1511
          free(fullname);
 
1512
          continue;
 
1513
        }
 
1514
      }
 
1515
      free(fullname);
 
1516
      if(debug){
 
1517
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1518
                     direntry->d_name);
 
1519
      }
 
1520
    }
 
1521
    close(devnull);
 
1522
  }
 
1523
  return true;
 
1524
}
 
1525
 
1343
1526
int main(int argc, char *argv[]){
1344
1527
  AvahiSServiceBrowser *sb = NULL;
1345
1528
  int error;
1425
1608
        .group = 2 },
1426
1609
      { .name = "retry", .key = 132,
1427
1610
        .arg = "SECONDS",
1428
 
        .doc = "Retry interval used when denied by the mandos server",
 
1611
        .doc = "Retry interval used when denied by the Mandos server",
 
1612
        .group = 2 },
 
1613
      { .name = "network-hook-dir", .key = 133,
 
1614
        .arg = "DIR",
 
1615
        .doc = "Directory where network hooks are located",
1429
1616
        .group = 2 },
1430
1617
      /*
1431
1618
       * These reproduce what we would get without ARGP_NO_HELP
1485
1672
          argp_error(state, "Bad retry interval");
1486
1673
        }
1487
1674
        break;
 
1675
      case 133:                 /* --network-hook-dir */
 
1676
        hookdir = arg;
 
1677
        break;
1488
1678
        /*
1489
1679
         * These reproduce what we would get without ARGP_NO_HELP
1490
1680
         */
1496
1686
        argp_state_help(state, state->out_stream,
1497
1687
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1498
1688
      case 'V':                 /* --version */
1499
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1689
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1500
1690
        exit(argp_err_exit_status);
1501
1691
        break;
1502
1692
      default:
1529
1719
  {
1530
1720
    /* Work around Debian bug #633582:
1531
1721
       <http://bugs.debian.org/633582> */
1532
 
    struct stat st;
1533
1722
    
1534
1723
    /* Re-raise priviliges */
1535
1724
    errno = 0;
1536
1725
    ret = seteuid(0);
1537
1726
    if(ret == -1){
1538
1727
      perror_plus("seteuid");
1539
 
    }
1540
 
    
1541
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1542
 
      int seckey_fd = open(seckey, O_RDONLY);
1543
 
      if(seckey_fd == -1){
1544
 
        perror_plus("open");
1545
 
      } else {
1546
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1547
 
        if(ret == -1){
1548
 
          perror_plus("fstat");
1549
 
        } else {
1550
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1551
 
            ret = fchown(seckey_fd, uid, gid);
1552
 
            if(ret == -1){
1553
 
              perror_plus("fchown");
1554
 
            }
1555
 
          }
1556
 
        }
1557
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1558
 
      }
1559
 
    }
1560
 
    
1561
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1562
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1563
 
      if(pubkey_fd == -1){
1564
 
        perror_plus("open");
1565
 
      } else {
1566
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1567
 
        if(ret == -1){
1568
 
          perror_plus("fstat");
1569
 
        } else {
1570
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1571
 
            ret = fchown(pubkey_fd, uid, gid);
1572
 
            if(ret == -1){
1573
 
              perror_plus("fchown");
1574
 
            }
1575
 
          }
1576
 
        }
1577
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1578
 
      }
1579
 
    }
1580
 
    
1581
 
    /* Lower privileges */
1582
 
    errno = 0;
1583
 
    ret = seteuid(uid);
1584
 
    if(ret == -1){
1585
 
      perror_plus("seteuid");
 
1728
    } else {
 
1729
      struct stat st;
 
1730
      
 
1731
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1732
        int seckey_fd = open(seckey, O_RDONLY);
 
1733
        if(seckey_fd == -1){
 
1734
          perror_plus("open");
 
1735
        } else {
 
1736
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1737
          if(ret == -1){
 
1738
            perror_plus("fstat");
 
1739
          } else {
 
1740
            if(S_ISREG(st.st_mode)
 
1741
               and st.st_uid == 0 and st.st_gid == 0){
 
1742
              ret = fchown(seckey_fd, uid, gid);
 
1743
              if(ret == -1){
 
1744
                perror_plus("fchown");
 
1745
              }
 
1746
            }
 
1747
          }
 
1748
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1749
        }
 
1750
      }
 
1751
    
 
1752
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1753
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1754
        if(pubkey_fd == -1){
 
1755
          perror_plus("open");
 
1756
        } else {
 
1757
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1758
          if(ret == -1){
 
1759
            perror_plus("fstat");
 
1760
          } else {
 
1761
            if(S_ISREG(st.st_mode)
 
1762
               and st.st_uid == 0 and st.st_gid == 0){
 
1763
              ret = fchown(pubkey_fd, uid, gid);
 
1764
              if(ret == -1){
 
1765
                perror_plus("fchown");
 
1766
              }
 
1767
            }
 
1768
          }
 
1769
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1770
        }
 
1771
      }
 
1772
    
 
1773
      /* Lower privileges */
 
1774
      errno = 0;
 
1775
      ret = seteuid(uid);
 
1776
      if(ret == -1){
 
1777
        perror_plus("seteuid");
 
1778
      }
1586
1779
    }
1587
1780
  }
1588
1781
  
1589
 
  /* Find network hooks and run them */
1590
 
  {
1591
 
    struct dirent **direntries;
1592
 
    struct dirent *direntry;
1593
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1594
 
                           alphasort);
1595
 
    int devnull = open("/dev/null", O_RDONLY);
1596
 
    for(int i = 0; i < numhooks; i++){
1597
 
      direntry = direntries[0];
1598
 
      char *fullname = NULL;
1599
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1600
 
                     direntry->d_name);
1601
 
      if(ret < 0){
1602
 
        perror_plus("asprintf");
1603
 
        continue;
1604
 
      }
1605
 
      pid_t hook_pid = fork();
1606
 
      if(hook_pid == 0){
1607
 
        /* Child */
1608
 
        dup2(devnull, STDIN_FILENO);
1609
 
        close(devnull);
1610
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1611
 
        setenv("DEVICE", interface, 1);
1612
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1613
 
        setenv("MODE", "start", 1);
1614
 
        /* setenv( XXX more here */
1615
 
        ret = execl(fullname, direntry->d_name, "start", NULL);
1616
 
        perror_plus("execl");
1617
 
      }
1618
 
      free(fullname);
1619
 
      if(quit_now){
1620
 
        goto end;
1621
 
      }
1622
 
    }
1623
 
    close(devnull);
 
1782
  /* Run network hooks */
 
1783
  if(not run_network_hooks("start", interface, delay)){
 
1784
    goto end;
1624
1785
  }
1625
1786
  
1626
1787
  if(not debug){
1642
1803
      /* Pick the first interface returned */
1643
1804
      interface = strdup(direntries[0]->d_name);
1644
1805
      if(debug){
1645
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1806
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1646
1807
      }
1647
1808
      if(interface == NULL){
1648
1809
        perror_plus("malloc");
1653
1814
      free(direntries);
1654
1815
    } else {
1655
1816
      free(direntries);
1656
 
      fprintf(stderr, "Could not find a network interface\n");
 
1817
      fprintf_plus(stderr, "Could not find a network interface\n");
1657
1818
      exitcode = EXIT_FAILURE;
1658
1819
      goto end;
1659
1820
    }
1665
1826
  srand((unsigned int) time(NULL));
1666
1827
  mc.simple_poll = avahi_simple_poll_new();
1667
1828
  if(mc.simple_poll == NULL){
1668
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1829
    fprintf_plus(stderr,
 
1830
                 "Avahi: Failed to create simple poll object.\n");
1669
1831
    exitcode = EX_UNAVAILABLE;
1670
1832
    goto end;
1671
1833
  }
1737
1899
  if(strcmp(interface, "none") != 0){
1738
1900
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1739
1901
    if(if_index == 0){
1740
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1902
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1741
1903
      exitcode = EX_UNAVAILABLE;
1742
1904
      goto end;
1743
1905
    }
1863
2025
#endif  /* __linux__ */
1864
2026
    /* Lower privileges */
1865
2027
    errno = 0;
1866
 
    if(take_down_interface){
1867
 
      /* Lower privileges */
1868
 
      ret = seteuid(uid);
1869
 
      if(ret == -1){
1870
 
        perror_plus("seteuid");
1871
 
      }
1872
 
    } else {
1873
 
      /* Lower privileges permanently */
1874
 
      ret = setuid(uid);
1875
 
      if(ret == -1){
1876
 
        perror_plus("setuid");
1877
 
      }
 
2028
    /* Lower privileges */
 
2029
    ret = seteuid(uid);
 
2030
    if(ret == -1){
 
2031
      perror_plus("seteuid");
1878
2032
    }
1879
2033
  }
1880
2034
  
1884
2038
  
1885
2039
  ret = init_gnutls_global(pubkey, seckey);
1886
2040
  if(ret == -1){
1887
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2041
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1888
2042
    exitcode = EX_UNAVAILABLE;
1889
2043
    goto end;
1890
2044
  } else {
1906
2060
  }
1907
2061
  
1908
2062
  if(not init_gpgme(pubkey, seckey, tempdir)){
1909
 
    fprintf(stderr, "init_gpgme failed\n");
 
2063
    fprintf_plus(stderr, "init_gpgme failed\n");
1910
2064
    exitcode = EX_UNAVAILABLE;
1911
2065
    goto end;
1912
2066
  } else {
1922
2076
    /* (Mainly meant for debugging) */
1923
2077
    char *address = strrchr(connect_to, ':');
1924
2078
    if(address == NULL){
1925
 
      fprintf(stderr, "No colon in address\n");
 
2079
      fprintf_plus(stderr, "No colon in address\n");
1926
2080
      exitcode = EX_USAGE;
1927
2081
      goto end;
1928
2082
    }
1936
2090
    tmpmax = strtoimax(address+1, &tmp, 10);
1937
2091
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1938
2092
       or tmpmax != (uint16_t)tmpmax){
1939
 
      fprintf(stderr, "Bad port number\n");
 
2093
      fprintf_plus(stderr, "Bad port number\n");
1940
2094
      exitcode = EX_USAGE;
1941
2095
      goto end;
1942
2096
    }
1972
2126
        break;
1973
2127
      }
1974
2128
      if(debug){
1975
 
        fprintf(stderr, "Retrying in %d seconds\n",
1976
 
                (int)retry_interval);
 
2129
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2130
                     (int)retry_interval);
1977
2131
      }
1978
2132
      sleep((int)retry_interval);
1979
2133
    }
2009
2163
  
2010
2164
  /* Check if creating the Avahi server object succeeded */
2011
2165
  if(mc.server == NULL){
2012
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2013
 
            avahi_strerror(error));
 
2166
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2167
                 avahi_strerror(error));
2014
2168
    exitcode = EX_UNAVAILABLE;
2015
2169
    goto end;
2016
2170
  }
2024
2178
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2025
2179
                                   NULL, 0, browse_callback, NULL);
2026
2180
  if(sb == NULL){
2027
 
    fprintf(stderr, "Failed to create service browser: %s\n",
2028
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2181
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2182
                 avahi_strerror(avahi_server_errno(mc.server)));
2029
2183
    exitcode = EX_UNAVAILABLE;
2030
2184
    goto end;
2031
2185
  }
2037
2191
  /* Run the main loop */
2038
2192
  
2039
2193
  if(debug){
2040
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2194
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2041
2195
  }
2042
2196
 
2043
2197
  ret = avahi_loop_with_timeout(mc.simple_poll,
2044
2198
                                (int)(retry_interval * 1000));
2045
2199
  if(debug){
2046
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2047
 
            (ret == 0) ? "successfully" : "with error");
 
2200
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2201
                 (ret == 0) ? "successfully" : "with error");
2048
2202
  }
2049
2203
  
2050
2204
 end:
2051
2205
  
2052
2206
  if(debug){
2053
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2207
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2054
2208
  }
2055
2209
  
2056
2210
  /* Cleanup things */
2072
2226
  if(gpgme_initialized){
2073
2227
    gpgme_release(mc.ctx);
2074
2228
  }
2075
 
 
 
2229
  
2076
2230
  /* Cleans up the circular linked list of Mandos servers the client
2077
2231
     has seen */
2078
2232
  if(mc.current_server != NULL){
2084
2238
    }
2085
2239
  }
2086
2240
  
2087
 
  /* XXX run network hooks "stop" here  */
 
2241
  /* Run network hooks */
 
2242
  run_network_hooks("stop", interface, delay);
2088
2243
  
2089
 
  /* Take down the network interface */
2090
 
  if(take_down_interface){
2091
 
    /* Re-raise priviliges */
 
2244
  /* Re-raise priviliges */
 
2245
  {
2092
2246
    errno = 0;
2093
2247
    ret = seteuid(0);
2094
2248
    if(ret == -1){
2095
2249
      perror_plus("seteuid");
2096
2250
    }
2097
 
    if(geteuid() == 0){
 
2251
    
 
2252
    /* Take down the network interface */
 
2253
    if(take_down_interface and geteuid() == 0){
2098
2254
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2099
2255
      if(ret == -1){
2100
2256
        perror_plus("ioctl SIOCGIFFLAGS");
2101
 
      } else if(network.ifr_flags & IFF_UP) {
 
2257
      } else if(network.ifr_flags & IFF_UP){
2102
2258
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2103
2259
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2104
2260
        if(ret == -1){
2109
2265
      if(ret == -1){
2110
2266
        perror_plus("close");
2111
2267
      }
2112
 
      /* Lower privileges permanently */
2113
 
      errno = 0;
2114
 
      ret = setuid(uid);
2115
 
      if(ret == -1){
2116
 
        perror_plus("setuid");
2117
 
      }
2118
2268
    }
2119
2269
  }
 
2270
  /* Lower privileges permanently */
 
2271
  errno = 0;
 
2272
  ret = setuid(uid);
 
2273
  if(ret == -1){
 
2274
    perror_plus("setuid");
 
2275
  }
2120
2276
  
2121
2277
  /* Removes the GPGME temp directory and all files inside */
2122
2278
  if(tempdir_created){
2136
2292
        }
2137
2293
        ret = remove(fullname);
2138
2294
        if(ret == -1){
2139
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2140
 
                  strerror(errno));
 
2295
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2296
                       strerror(errno));
2141
2297
        }
2142
2298
        free(fullname);
2143
2299
      }