/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-05-17 01:55:58 UTC
  • Revision ID: teddy@recompile.se-20120517015558-5703p8nkquc2rhgd
* .bzrignore (statedir): Added.

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
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
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)))
174
181
int fprintf_plus(FILE *stream, const char *format, ...){
175
182
  va_list ap;
176
183
  va_start (ap, format);
177
184
  
178
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
185
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
186
                             program_invocation_short_name));
179
187
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
180
188
}
181
189
 
185
193
 * "buffer_length" is how much is already used.
186
194
 */
187
195
size_t incbuffer(char **buffer, size_t buffer_length,
188
 
                  size_t buffer_capacity){
 
196
                 size_t buffer_capacity){
189
197
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
190
198
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
191
199
    if(buffer == NULL){
197
205
}
198
206
 
199
207
/* Add server to set of servers to retry periodically */
200
 
int add_server(const char *ip, uint16_t port,
201
 
                 AvahiIfIndex if_index,
202
 
                 int af){
 
208
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
209
                int af){
203
210
  int ret;
204
211
  server *new_server = malloc(sizeof(server));
205
212
  if(new_server == NULL){
206
213
    perror_plus("malloc");
207
 
    return -1;
 
214
    return false;
208
215
  }
209
216
  *new_server = (server){ .ip = strdup(ip),
210
 
                         .port = port,
211
 
                         .if_index = if_index,
212
 
                         .af = af };
 
217
                          .port = port,
 
218
                          .if_index = if_index,
 
219
                          .af = af };
213
220
  if(new_server->ip == NULL){
214
221
    perror_plus("strdup");
215
 
    return -1;
 
222
    return false;
216
223
  }
217
224
  /* Special case of first server */
218
225
  if (mc.current_server == NULL){
229
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
230
237
  if(ret == -1){
231
238
    perror_plus("clock_gettime");
232
 
    return -1;
 
239
    return false;
233
240
  }
234
 
  return 0;
 
241
  return true;
235
242
}
236
243
 
237
244
/* 
238
245
 * Initialize GPGME.
239
246
 */
240
 
static bool init_gpgme(const char *seckey,
241
 
                       const char *pubkey, const char *tempdir){
 
247
static bool init_gpgme(const char *seckey, const char *pubkey,
 
248
                       const char *tempdir){
242
249
  gpgme_error_t rc;
243
250
  gpgme_engine_info_t engine_info;
244
251
  
259
266
    
260
267
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
261
268
    if(rc != GPG_ERR_NO_ERROR){
262
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
263
 
              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));
264
271
      return false;
265
272
    }
266
273
    
267
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
268
275
    if(rc != GPG_ERR_NO_ERROR){
269
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
270
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
271
278
      return false;
272
279
    }
273
280
    
280
287
  }
281
288
  
282
289
  if(debug){
283
 
    fprintf(stderr, "Initializing GPGME\n");
 
290
    fprintf_plus(stderr, "Initializing GPGME\n");
284
291
  }
285
292
  
286
293
  /* Init GPGME */
287
294
  gpgme_check_version(NULL);
288
295
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
289
296
  if(rc != GPG_ERR_NO_ERROR){
290
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
291
 
            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));
292
299
    return false;
293
300
  }
294
301
  
295
302
  /* Set GPGME home directory for the OpenPGP engine only */
296
303
  rc = gpgme_get_engine_info(&engine_info);
297
304
  if(rc != GPG_ERR_NO_ERROR){
298
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
299
 
            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));
300
307
    return false;
301
308
  }
302
309
  while(engine_info != NULL){
308
315
    engine_info = engine_info->next;
309
316
  }
310
317
  if(engine_info == NULL){
311
 
    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);
312
320
    return false;
313
321
  }
314
322
  
315
323
  /* Create new GPGME "context" */
316
324
  rc = gpgme_new(&(mc.ctx));
317
325
  if(rc != GPG_ERR_NO_ERROR){
318
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
319
 
            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));
320
329
    return false;
321
330
  }
322
331
  
341
350
  ssize_t plaintext_length = 0;
342
351
  
343
352
  if(debug){
344
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
353
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
345
354
  }
346
355
  
347
356
  /* Create new GPGME data buffer from memory cryptotext */
348
357
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
349
358
                               0);
350
359
  if(rc != GPG_ERR_NO_ERROR){
351
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
352
 
            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));
353
362
    return -1;
354
363
  }
355
364
  
356
365
  /* Create new empty GPGME data buffer for the plaintext */
357
366
  rc = gpgme_data_new(&dh_plain);
358
367
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
360
 
            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));
361
371
    gpgme_data_release(dh_crypto);
362
372
    return -1;
363
373
  }
366
376
     data buffer */
367
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
368
378
  if(rc != GPG_ERR_NO_ERROR){
369
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
370
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
371
381
    plaintext_length = -1;
372
382
    if(debug){
373
383
      gpgme_decrypt_result_t result;
374
384
      result = gpgme_op_decrypt_result(mc.ctx);
375
385
      if(result == NULL){
376
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
377
387
      } else {
378
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
379
 
                result->unsupported_algorithm);
380
 
        fprintf(stderr, "Wrong key usage: %u\n",
381
 
                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);
382
392
        if(result->file_name != NULL){
383
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
393
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
384
394
        }
385
395
        gpgme_recipient_t recipient;
386
396
        recipient = result->recipients;
387
397
        while(recipient != NULL){
388
 
          fprintf(stderr, "Public key algorithm: %s\n",
389
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
390
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
391
 
          fprintf(stderr, "Secret key available: %s\n",
392
 
                  recipient->status == GPG_ERR_NO_SECKEY
393
 
                  ? "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");
394
405
          recipient = recipient->next;
395
406
        }
396
407
      }
399
410
  }
400
411
  
401
412
  if(debug){
402
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
413
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
403
414
  }
404
415
  
405
416
  /* Seek back to the beginning of the GPGME plaintext data buffer */
412
423
  *plaintext = NULL;
413
424
  while(true){
414
425
    plaintext_capacity = incbuffer(plaintext,
415
 
                                      (size_t)plaintext_length,
416
 
                                      plaintext_capacity);
 
426
                                   (size_t)plaintext_length,
 
427
                                   plaintext_capacity);
417
428
    if(plaintext_capacity == 0){
418
 
        perror_plus("incbuffer");
419
 
        plaintext_length = -1;
420
 
        goto decrypt_end;
 
429
      perror_plus("incbuffer");
 
430
      plaintext_length = -1;
 
431
      goto decrypt_end;
421
432
    }
422
433
    
423
434
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
436
447
  }
437
448
  
438
449
  if(debug){
439
 
    fprintf(stderr, "Decrypted password is: ");
 
450
    fprintf_plus(stderr, "Decrypted password is: ");
440
451
    for(ssize_t i = 0; i < plaintext_length; i++){
441
452
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
442
453
    }
464
475
/* GnuTLS log function callback */
465
476
static void debuggnutls(__attribute__((unused)) int level,
466
477
                        const char* string){
467
 
  fprintf(stderr, "GnuTLS: %s", string);
 
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
468
479
}
469
480
 
470
481
static int init_gnutls_global(const char *pubkeyfilename,
472
483
  int ret;
473
484
  
474
485
  if(debug){
475
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
486
    fprintf_plus(stderr, "Initializing GnuTLS\n");
476
487
  }
477
488
  
478
489
  ret = gnutls_global_init();
479
490
  if(ret != GNUTLS_E_SUCCESS){
480
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
481
 
            safer_gnutls_strerror(ret));
 
491
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
492
                 safer_gnutls_strerror(ret));
482
493
    return -1;
483
494
  }
484
495
  
493
504
  /* OpenPGP credentials */
494
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
495
506
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
497
 
            safer_gnutls_strerror(ret));
 
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
508
                 safer_gnutls_strerror(ret));
498
509
    gnutls_global_deinit();
499
510
    return -1;
500
511
  }
501
512
  
502
513
  if(debug){
503
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
504
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
505
 
            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);
506
518
  }
507
519
  
508
520
  ret = gnutls_certificate_set_openpgp_key_file
509
521
    (mc.cred, pubkeyfilename, seckeyfilename,
510
522
     GNUTLS_OPENPGP_FMT_BASE64);
511
523
  if(ret != GNUTLS_E_SUCCESS){
512
 
    fprintf(stderr,
513
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
514
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
515
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
516
 
            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));
517
529
    goto globalfail;
518
530
  }
519
531
  
520
532
  /* GnuTLS server initialization */
521
533
  ret = gnutls_dh_params_init(&mc.dh_params);
522
534
  if(ret != GNUTLS_E_SUCCESS){
523
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
524
 
            " %s\n", safer_gnutls_strerror(ret));
 
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
536
                 " initialization: %s\n",
 
537
                 safer_gnutls_strerror(ret));
525
538
    goto globalfail;
526
539
  }
527
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
528
541
  if(ret != GNUTLS_E_SUCCESS){
529
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
530
 
            safer_gnutls_strerror(ret));
 
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
543
                 safer_gnutls_strerror(ret));
531
544
    goto globalfail;
532
545
  }
533
546
  
553
566
    }
554
567
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
555
568
  if(ret != GNUTLS_E_SUCCESS){
556
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
557
 
            safer_gnutls_strerror(ret));
 
569
    fprintf_plus(stderr,
 
570
                 "Error in GnuTLS session initialization: %s\n",
 
571
                 safer_gnutls_strerror(ret));
558
572
  }
559
573
  
560
574
  {
567
581
      }
568
582
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
569
583
    if(ret != GNUTLS_E_SUCCESS){
570
 
      fprintf(stderr, "Syntax error at: %s\n", err);
571
 
      fprintf(stderr, "GnuTLS error: %s\n",
572
 
              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));
573
587
      gnutls_deinit(*session);
574
588
      return -1;
575
589
    }
584
598
    }
585
599
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
586
600
  if(ret != GNUTLS_E_SUCCESS){
587
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
588
 
            safer_gnutls_strerror(ret));
 
601
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
602
                 safer_gnutls_strerror(ret));
589
603
    gnutls_deinit(*session);
590
604
    return -1;
591
605
  }
636
650
    pf = PF_INET;
637
651
    break;
638
652
  default:
639
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
653
    fprintf_plus(stderr, "Bad address family: %d\n", af);
640
654
    errno = EINVAL;
641
655
    return -1;
642
656
  }
647
661
  }
648
662
  
649
663
  if(debug){
650
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
651
 
            "\n", ip, port);
 
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
665
                 PRIu16 "\n", ip, port);
652
666
  }
653
667
  
654
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
680
694
  }
681
695
  if(ret == 0){
682
696
    int e = errno;
683
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
697
    fprintf_plus(stderr, "Bad address: %s\n", ip);
684
698
    errno = e;
685
699
    goto mandos_end;
686
700
  }
691
705
    
692
706
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
693
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
694
 
                              -Wunreachable-code*/
 
708
                                -Wunreachable-code*/
695
709
      if(if_index == AVAHI_IF_UNSPEC){
696
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
697
 
                " without a network interface\n");
 
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
711
                     " incomplete without a network interface\n");
698
712
        errno = EINVAL;
699
713
        goto mandos_end;
700
714
      }
718
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
719
733
        perror_plus("if_indextoname");
720
734
      } else {
721
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
722
 
                ip, interface, port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
723
737
      }
724
738
    } else {
725
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
726
 
              port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
727
741
    }
728
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
729
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
739
753
      perror_plus("inet_ntop");
740
754
    } else {
741
755
      if(strcmp(addrstr, ip) != 0){
742
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
743
757
      }
744
758
    }
745
759
  }
773
787
  while(true){
774
788
    size_t out_size = strlen(out);
775
789
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
776
 
                                   out_size - written));
 
790
                                        out_size - written));
777
791
    if(ret == -1){
778
792
      int e = errno;
779
793
      perror_plus("write");
799
813
  }
800
814
  
801
815
  if(debug){
802
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
816
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
803
817
  }
804
818
  
805
819
  if(quit_now){
825
839
  
826
840
  if(ret != GNUTLS_E_SUCCESS){
827
841
    if(debug){
828
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
842
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
829
843
      gnutls_perror(ret);
830
844
    }
831
845
    errno = EPROTO;
835
849
  /* Read OpenPGP packet that contains the wanted password */
836
850
  
837
851
  if(debug){
838
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
839
 
            ip);
 
852
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
853
                 " %s\n", ip);
840
854
  }
841
855
  
842
856
  while(true){
847
861
    }
848
862
    
849
863
    buffer_capacity = incbuffer(&buffer, buffer_length,
850
 
                                   buffer_capacity);
 
864
                                buffer_capacity);
851
865
    if(buffer_capacity == 0){
852
866
      int e = errno;
853
867
      perror_plus("incbuffer");
880
894
          }
881
895
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
882
896
        if(ret < 0){
883
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
897
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
898
                       "***\n");
884
899
          gnutls_perror(ret);
885
900
          errno = EPROTO;
886
901
          goto mandos_end;
887
902
        }
888
903
        break;
889
904
      default:
890
 
        fprintf(stderr, "Unknown error while reading data from"
891
 
                " encrypted session with Mandos server\n");
 
905
        fprintf_plus(stderr, "Unknown error while reading data from"
 
906
                     " encrypted session with Mandos server\n");
892
907
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
893
908
        errno = EIO;
894
909
        goto mandos_end;
899
914
  }
900
915
  
901
916
  if(debug){
902
 
    fprintf(stderr, "Closing TLS session\n");
 
917
    fprintf_plus(stderr, "Closing TLS session\n");
903
918
  }
904
919
  
905
920
  if(quit_now){
917
932
  
918
933
  if(buffer_length > 0){
919
934
    ssize_t decrypted_buffer_size;
920
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
921
 
                                               buffer_length,
 
935
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
922
936
                                               &decrypted_buffer);
923
937
    if(decrypted_buffer_size >= 0){
924
938
      
935
949
        if(ret == 0 and ferror(stdout)){
936
950
          int e = errno;
937
951
          if(debug){
938
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
939
 
                    strerror(errno));
 
952
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
953
                         strerror(errno));
940
954
          }
941
955
          errno = e;
942
956
          goto mandos_end;
999
1013
  switch(event){
1000
1014
  default:
1001
1015
  case AVAHI_RESOLVER_FAILURE:
1002
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
1003
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1004
 
            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)));
1005
1020
    break;
1006
1021
    
1007
1022
  case AVAHI_RESOLVER_FOUND:
1009
1024
      char ip[AVAHI_ADDRESS_STR_MAX];
1010
1025
      avahi_address_snprint(ip, sizeof(ip), address);
1011
1026
      if(debug){
1012
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1013
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1014
 
                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);
1015
1030
      }
1016
1031
      int ret = start_mandos_communication(ip, port, interface,
1017
1032
                                           avahi_proto_to_af(proto));
1018
1033
      if(ret == 0){
1019
1034
        avahi_simple_poll_quit(mc.simple_poll);
1020
1035
      } else {
1021
 
        ret = add_server(ip, port, interface,
1022
 
                         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
        }
1023
1041
      }
1024
1042
    }
1025
1043
  }
1049
1067
  default:
1050
1068
  case AVAHI_BROWSER_FAILURE:
1051
1069
    
1052
 
    fprintf(stderr, "(Avahi browser) %s\n",
1053
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1070
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1071
                 avahi_strerror(avahi_server_errno(mc.server)));
1054
1072
    avahi_simple_poll_quit(mc.simple_poll);
1055
1073
    return;
1056
1074
    
1063
1081
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1064
1082
                                    name, type, domain, protocol, 0,
1065
1083
                                    resolve_callback, NULL) == NULL)
1066
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1067
 
              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)));
1068
1087
    break;
1069
1088
    
1070
1089
  case AVAHI_BROWSER_REMOVE:
1073
1092
  case AVAHI_BROWSER_ALL_FOR_NOW:
1074
1093
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1075
1094
    if(debug){
1076
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1095
      fprintf_plus(stderr, "No Mandos server found, still"
 
1096
                   " searching...\n");
1077
1097
    }
1078
1098
    break;
1079
1099
  }
1118
1138
  /* Reject the loopback device */
1119
1139
  if(ifr->ifr_flags & IFF_LOOPBACK){
1120
1140
    if(debug){
1121
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1122
 
              ifname);
 
1141
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1142
                   ifname);
1123
1143
    }
1124
1144
    return false;
1125
1145
  }
1126
1146
  /* Accept point-to-point devices only if connect_to is specified */
1127
1147
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1128
1148
    if(debug){
1129
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1130
 
              ifname);
 
1149
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1150
                   " \"%s\"\n", ifname);
1131
1151
    }
1132
1152
    return true;
1133
1153
  }
1134
1154
  /* Otherwise, reject non-broadcast-capable devices */
1135
1155
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1136
1156
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1138
 
              ifname);
 
1157
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1158
                   " \"%s\"\n", ifname);
1139
1159
    }
1140
1160
    return false;
1141
1161
  }
1142
1162
  /* Reject non-ARP interfaces (including dummy interfaces) */
1143
1163
  if(ifr->ifr_flags & IFF_NOARP){
1144
1164
    if(debug){
1145
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1165
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1166
                   ifname);
1146
1167
    }
1147
1168
    return false;
1148
1169
  }
1149
1170
  
1150
1171
  /* Accept this device */
1151
1172
  if(debug){
1152
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1173
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1153
1174
  }
1154
1175
  return true;
1155
1176
}
1160
1181
 * (This function is passed to scandir(3) as a filter function.)
1161
1182
 */
1162
1183
int good_interface(const struct dirent *if_entry){
1163
 
  int ret;
1164
1184
  if(if_entry->d_name[0] == '.'){
1165
1185
    return 0;
1166
1186
  }
 
1187
  
1167
1188
  struct ifreq ifr;
1168
 
 
1169
1189
  if(not get_flags(if_entry->d_name, &ifr)){
 
1190
    if(debug){
 
1191
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1192
                   "\"%s\"\n", if_entry->d_name);
 
1193
    }
1170
1194
    return 0;
1171
1195
  }
1172
1196
  
1182
1206
 * (This function is passed to scandir(3) as a filter function.)
1183
1207
 */
1184
1208
int up_interface(const struct dirent *if_entry){
1185
 
  ssize_t ssret;
1186
 
  char *flagname = NULL;
1187
1209
  if(if_entry->d_name[0] == '.'){
1188
1210
    return 0;
1189
1211
  }
1190
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1191
 
                     if_entry->d_name);
1192
 
  if(ret < 0){
1193
 
    perror_plus("asprintf");
1194
 
    return 0;
1195
 
  }
1196
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1197
 
  if(flags_fd == -1){
1198
 
    perror_plus("open");
1199
 
    free(flagname);
1200
 
    return 0;
1201
 
  }
1202
 
  free(flagname);
1203
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1204
 
  /* read line from flags_fd */
1205
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1206
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1207
 
  flagstring[(size_t)to_read] = '\0';
1208
 
  if(flagstring == NULL){
1209
 
    perror_plus("malloc");
1210
 
    close(flags_fd);
1211
 
    return 0;
1212
 
  }
1213
 
  while(to_read > 0){
1214
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1215
 
                                             (size_t)to_read));
1216
 
    if(ssret == -1){
1217
 
      perror_plus("read");
1218
 
      free(flagstring);
1219
 
      close(flags_fd);
1220
 
      return 0;
1221
 
    }
1222
 
    to_read -= ssret;
1223
 
    if(ssret == 0){
1224
 
      break;
1225
 
    }
1226
 
  }
1227
 
  close(flags_fd);
1228
 
  intmax_t tmpmax;
1229
 
  char *tmp;
1230
 
  errno = 0;
1231
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1232
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1233
 
                                         and not (isspace(*tmp)))
1234
 
     or tmpmax != (ifreq_flags)tmpmax){
1235
 
    if(debug){
1236
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1237
 
              flagstring, if_entry->d_name);
1238
 
    }
1239
 
    free(flagstring);
1240
 
    return 0;
1241
 
  }
1242
 
  free(flagstring);
1243
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
1244
 
  /* Reject the loopback device */
1245
 
  if(flags & IFF_LOOPBACK){
1246
 
    if(debug){
1247
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1248
 
              if_entry->d_name);
1249
 
    }
1250
 
    return 0;
1251
 
  }
1252
 
 
 
1212
  
 
1213
  struct ifreq ifr;
 
1214
  if(not get_flags(if_entry->d_name, &ifr)){
 
1215
    if(debug){
 
1216
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1217
                   "\"%s\"\n", if_entry->d_name);
 
1218
    }
 
1219
    return 0;
 
1220
  }
 
1221
  
1253
1222
  /* Reject down interfaces */
1254
 
  if(not (flags & IFF_UP)){
1255
 
    return 0;
1256
 
  }
1257
 
  
1258
 
  /* Accept point-to-point devices only if connect_to is specified */
1259
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1260
 
    if(debug){
1261
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1262
 
              if_entry->d_name);
1263
 
    }
1264
 
    return 1;
1265
 
  }
1266
 
  /* Otherwise, reject non-broadcast-capable devices */
1267
 
  if(not (flags & IFF_BROADCAST)){
1268
 
    if(debug){
1269
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1270
 
              if_entry->d_name);
1271
 
    }
1272
 
    return 0;
1273
 
  }
1274
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1275
 
  if(flags & IFF_NOARP){
1276
 
    if(debug){
1277
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1278
 
              if_entry->d_name);
1279
 
    }
1280
 
    return 0;
1281
 
  }
1282
 
  /* Accept this device */
1283
 
  if(debug){
1284
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1285
 
            if_entry->d_name);
 
1223
  if(not (ifr.ifr_flags & IFF_UP)){
 
1224
    if(debug){
 
1225
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1226
                   if_entry->d_name);
 
1227
    }
 
1228
    return 0;
 
1229
  }
 
1230
  
 
1231
  /* Reject non-running interfaces */
 
1232
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1233
    if(debug){
 
1234
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1235
                   if_entry->d_name);
 
1236
    }
 
1237
    return 0;
 
1238
  }
 
1239
  
 
1240
  if(not good_flags(if_entry->d_name, &ifr)){
 
1241
    return 0;
1286
1242
  }
1287
1243
  return 1;
1288
1244
}
1301
1257
/* Is this directory entry a runnable program? */
1302
1258
int runnable_hook(const struct dirent *direntry){
1303
1259
  int ret;
 
1260
  size_t sret;
1304
1261
  struct stat st;
1305
1262
  
1306
1263
  if((direntry->d_name)[0] == '\0'){
1308
1265
    return 0;
1309
1266
  }
1310
1267
  
1311
 
  /* Save pointer to last character */
1312
 
  char *end = strchr(direntry->d_name, '\0')-1;
1313
 
  
1314
 
  if(*end == '~'){
1315
 
    /* Backup name~ */
1316
 
    return 0;
1317
 
  }
1318
 
  
1319
 
  if(((direntry->d_name)[0] == '#')
1320
 
     and (*end == '#')){
1321
 
    /* Temporary #name# */
1322
 
    return 0;
1323
 
  }
1324
 
  
1325
 
  /* XXX more rules here */
1326
 
  
1327
 
  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);
1328
1289
  if(ret == -1){
1329
1290
    if(debug){
1330
 
      perror_plus("Could not stat plugin");
 
1291
      perror_plus("Could not stat hook");
1331
1292
    }
1332
1293
    return 0;
1333
1294
  }
1334
 
  if(not (st.st_mode & S_ISREG)){
 
1295
  if(not (S_ISREG(st.st_mode))){
1335
1296
    /* Not a regular file */
 
1297
    if(debug){
 
1298
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1299
                   direntry->d_name);
 
1300
    }
1336
1301
    return 0;
1337
1302
  }
1338
1303
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1339
1304
    /* Not executable */
 
1305
    if(debug){
 
1306
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1307
                   direntry->d_name);
 
1308
    }
1340
1309
    return 0;
1341
1310
  }
 
1311
  if(debug){
 
1312
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1313
                 direntry->d_name);
 
1314
  }
1342
1315
  return 1;
1343
1316
}
1344
1317
 
1351
1324
  while(true){
1352
1325
    if(mc.current_server == NULL){
1353
1326
      if (debug){
1354
 
        fprintf(stderr,
1355
 
                "Wait until first server is found. No timeout!\n");
 
1327
        fprintf_plus(stderr, "Wait until first server is found."
 
1328
                     " No timeout!\n");
1356
1329
      }
1357
1330
      ret = avahi_simple_poll_iterate(s, -1);
1358
1331
    } else {
1359
1332
      if (debug){
1360
 
        fprintf(stderr, "Check current_server if we should run it,"
1361
 
                " or wait\n");
 
1333
        fprintf_plus(stderr, "Check current_server if we should run"
 
1334
                     " it, or wait\n");
1362
1335
      }
1363
1336
      /* the current time */
1364
1337
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1380
1353
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1381
1354
      
1382
1355
      if (debug){
1383
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1356
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1357
                     block_time);
1384
1358
      }
1385
1359
      
1386
1360
      if(block_time <= 0){
1406
1380
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1407
1381
    }
1408
1382
    if(ret != 0){
1409
 
      if (ret > 0 or errno != EINTR) {
 
1383
      if (ret > 0 or errno != EINTR){
1410
1384
        return (ret != 1) ? ret : 0;
1411
1385
      }
1412
1386
    }
1413
1387
  }
1414
1388
}
1415
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
 
1416
1526
int main(int argc, char *argv[]){
1417
1527
  AvahiSServiceBrowser *sb = NULL;
1418
1528
  int error;
1498
1608
        .group = 2 },
1499
1609
      { .name = "retry", .key = 132,
1500
1610
        .arg = "SECONDS",
1501
 
        .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",
1502
1616
        .group = 2 },
1503
1617
      /*
1504
1618
       * These reproduce what we would get without ARGP_NO_HELP
1558
1672
          argp_error(state, "Bad retry interval");
1559
1673
        }
1560
1674
        break;
 
1675
      case 133:                 /* --network-hook-dir */
 
1676
        hookdir = arg;
 
1677
        break;
1561
1678
        /*
1562
1679
         * These reproduce what we would get without ARGP_NO_HELP
1563
1680
         */
1569
1686
        argp_state_help(state, state->out_stream,
1570
1687
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1571
1688
      case 'V':                 /* --version */
1572
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1689
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1573
1690
        exit(argp_err_exit_status);
1574
1691
        break;
1575
1692
      default:
1602
1719
  {
1603
1720
    /* Work around Debian bug #633582:
1604
1721
       <http://bugs.debian.org/633582> */
1605
 
    struct stat st;
1606
1722
    
1607
1723
    /* Re-raise priviliges */
1608
1724
    errno = 0;
1609
1725
    ret = seteuid(0);
1610
1726
    if(ret == -1){
1611
1727
      perror_plus("seteuid");
1612
 
    }
1613
 
    
1614
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1615
 
      int seckey_fd = open(seckey, O_RDONLY);
1616
 
      if(seckey_fd == -1){
1617
 
        perror_plus("open");
1618
 
      } else {
1619
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1620
 
        if(ret == -1){
1621
 
          perror_plus("fstat");
1622
 
        } else {
1623
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1624
 
            ret = fchown(seckey_fd, uid, gid);
1625
 
            if(ret == -1){
1626
 
              perror_plus("fchown");
1627
 
            }
1628
 
          }
1629
 
        }
1630
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1631
 
      }
1632
 
    }
1633
 
    
1634
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1635
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1636
 
      if(pubkey_fd == -1){
1637
 
        perror_plus("open");
1638
 
      } else {
1639
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1640
 
        if(ret == -1){
1641
 
          perror_plus("fstat");
1642
 
        } else {
1643
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1644
 
            ret = fchown(pubkey_fd, uid, gid);
1645
 
            if(ret == -1){
1646
 
              perror_plus("fchown");
1647
 
            }
1648
 
          }
1649
 
        }
1650
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1651
 
      }
1652
 
    }
1653
 
    
1654
 
    /* Lower privileges */
1655
 
    errno = 0;
1656
 
    ret = seteuid(uid);
1657
 
    if(ret == -1){
1658
 
      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
      }
1659
1779
    }
1660
1780
  }
1661
1781
  
1662
 
  /* Find network hooks and run them */
1663
 
  {
1664
 
    struct dirent **direntries;
1665
 
    struct dirent *direntry;
1666
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1667
 
                           alphasort);
1668
 
    int devnull = open("/dev/null", O_RDONLY);
1669
 
    for(int i = 0; i < numhooks; i++){
1670
 
      direntry = direntries[0];
1671
 
      char *fullname = NULL;
1672
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1673
 
                     direntry->d_name);
1674
 
      if(ret < 0){
1675
 
        perror_plus("asprintf");
1676
 
        continue;
1677
 
      }
1678
 
      pid_t hook_pid = fork();
1679
 
      if(hook_pid == 0){
1680
 
        /* Child */
1681
 
        dup2(devnull, STDIN_FILENO);
1682
 
        close(devnull);
1683
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1684
 
        setenv("DEVICE", interface, 1);
1685
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1686
 
        setenv("MODE", "start", 1);
1687
 
        /* setenv( XXX more here */
1688
 
        ret = execl(fullname, direntry->d_name, "start");
1689
 
        perror_plus("execl");
1690
 
      }
1691
 
      free(fullname);
1692
 
      if(quit_now){
1693
 
        goto end;
1694
 
      }
1695
 
    }
1696
 
    close(devnull);
 
1782
  /* Run network hooks */
 
1783
  if(not run_network_hooks("start", interface, delay)){
 
1784
    goto end;
1697
1785
  }
1698
1786
  
1699
1787
  if(not debug){
1702
1790
  
1703
1791
  if(interface[0] == '\0'){
1704
1792
    struct dirent **direntries;
1705
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1793
    /* First look for interfaces that are up */
 
1794
    ret = scandir(sys_class_net, &direntries, up_interface,
1706
1795
                  alphasort);
 
1796
    if(ret == 0){
 
1797
      /* No up interfaces, look for any good interfaces */
 
1798
      free(direntries);
 
1799
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1800
                    alphasort);
 
1801
    }
1707
1802
    if(ret >= 1){
1708
 
      /* Pick the first good interface */
 
1803
      /* Pick the first interface returned */
1709
1804
      interface = strdup(direntries[0]->d_name);
1710
1805
      if(debug){
1711
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1806
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1712
1807
      }
1713
1808
      if(interface == NULL){
1714
1809
        perror_plus("malloc");
1719
1814
      free(direntries);
1720
1815
    } else {
1721
1816
      free(direntries);
1722
 
      fprintf(stderr, "Could not find a network interface\n");
 
1817
      fprintf_plus(stderr, "Could not find a network interface\n");
1723
1818
      exitcode = EXIT_FAILURE;
1724
1819
      goto end;
1725
1820
    }
1731
1826
  srand((unsigned int) time(NULL));
1732
1827
  mc.simple_poll = avahi_simple_poll_new();
1733
1828
  if(mc.simple_poll == NULL){
1734
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1829
    fprintf_plus(stderr,
 
1830
                 "Avahi: Failed to create simple poll object.\n");
1735
1831
    exitcode = EX_UNAVAILABLE;
1736
1832
    goto end;
1737
1833
  }
1803
1899
  if(strcmp(interface, "none") != 0){
1804
1900
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1805
1901
    if(if_index == 0){
1806
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1902
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1807
1903
      exitcode = EX_UNAVAILABLE;
1808
1904
      goto end;
1809
1905
    }
1929
2025
#endif  /* __linux__ */
1930
2026
    /* Lower privileges */
1931
2027
    errno = 0;
1932
 
    if(take_down_interface){
1933
 
      /* Lower privileges */
1934
 
      ret = seteuid(uid);
1935
 
      if(ret == -1){
1936
 
        perror_plus("seteuid");
1937
 
      }
1938
 
    } else {
1939
 
      /* Lower privileges permanently */
1940
 
      ret = setuid(uid);
1941
 
      if(ret == -1){
1942
 
        perror_plus("setuid");
1943
 
      }
 
2028
    /* Lower privileges */
 
2029
    ret = seteuid(uid);
 
2030
    if(ret == -1){
 
2031
      perror_plus("seteuid");
1944
2032
    }
1945
2033
  }
1946
2034
  
1950
2038
  
1951
2039
  ret = init_gnutls_global(pubkey, seckey);
1952
2040
  if(ret == -1){
1953
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2041
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1954
2042
    exitcode = EX_UNAVAILABLE;
1955
2043
    goto end;
1956
2044
  } else {
1972
2060
  }
1973
2061
  
1974
2062
  if(not init_gpgme(pubkey, seckey, tempdir)){
1975
 
    fprintf(stderr, "init_gpgme failed\n");
 
2063
    fprintf_plus(stderr, "init_gpgme failed\n");
1976
2064
    exitcode = EX_UNAVAILABLE;
1977
2065
    goto end;
1978
2066
  } else {
1988
2076
    /* (Mainly meant for debugging) */
1989
2077
    char *address = strrchr(connect_to, ':');
1990
2078
    if(address == NULL){
1991
 
      fprintf(stderr, "No colon in address\n");
 
2079
      fprintf_plus(stderr, "No colon in address\n");
1992
2080
      exitcode = EX_USAGE;
1993
2081
      goto end;
1994
2082
    }
2002
2090
    tmpmax = strtoimax(address+1, &tmp, 10);
2003
2091
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2004
2092
       or tmpmax != (uint16_t)tmpmax){
2005
 
      fprintf(stderr, "Bad port number\n");
 
2093
      fprintf_plus(stderr, "Bad port number\n");
2006
2094
      exitcode = EX_USAGE;
2007
2095
      goto end;
2008
2096
    }
2038
2126
        break;
2039
2127
      }
2040
2128
      if(debug){
2041
 
        fprintf(stderr, "Retrying in %d seconds\n",
2042
 
                (int)retry_interval);
 
2129
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2130
                     (int)retry_interval);
2043
2131
      }
2044
2132
      sleep((int)retry_interval);
2045
2133
    }
2075
2163
  
2076
2164
  /* Check if creating the Avahi server object succeeded */
2077
2165
  if(mc.server == NULL){
2078
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2079
 
            avahi_strerror(error));
 
2166
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2167
                 avahi_strerror(error));
2080
2168
    exitcode = EX_UNAVAILABLE;
2081
2169
    goto end;
2082
2170
  }
2090
2178
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2091
2179
                                   NULL, 0, browse_callback, NULL);
2092
2180
  if(sb == NULL){
2093
 
    fprintf(stderr, "Failed to create service browser: %s\n",
2094
 
            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)));
2095
2183
    exitcode = EX_UNAVAILABLE;
2096
2184
    goto end;
2097
2185
  }
2103
2191
  /* Run the main loop */
2104
2192
  
2105
2193
  if(debug){
2106
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2194
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2107
2195
  }
2108
2196
 
2109
2197
  ret = avahi_loop_with_timeout(mc.simple_poll,
2110
2198
                                (int)(retry_interval * 1000));
2111
2199
  if(debug){
2112
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2113
 
            (ret == 0) ? "successfully" : "with error");
 
2200
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2201
                 (ret == 0) ? "successfully" : "with error");
2114
2202
  }
2115
2203
  
2116
2204
 end:
2117
2205
  
2118
2206
  if(debug){
2119
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2207
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2120
2208
  }
2121
2209
  
2122
2210
  /* Cleanup things */
2138
2226
  if(gpgme_initialized){
2139
2227
    gpgme_release(mc.ctx);
2140
2228
  }
2141
 
 
 
2229
  
2142
2230
  /* Cleans up the circular linked list of Mandos servers the client
2143
2231
     has seen */
2144
2232
  if(mc.current_server != NULL){
2150
2238
    }
2151
2239
  }
2152
2240
  
2153
 
  /* XXX run network hooks "stop" here  */
 
2241
  /* Run network hooks */
 
2242
  run_network_hooks("stop", interface, delay);
2154
2243
  
2155
 
  /* Take down the network interface */
2156
 
  if(take_down_interface){
2157
 
    /* Re-raise priviliges */
 
2244
  /* Re-raise priviliges */
 
2245
  {
2158
2246
    errno = 0;
2159
2247
    ret = seteuid(0);
2160
2248
    if(ret == -1){
2161
2249
      perror_plus("seteuid");
2162
2250
    }
2163
 
    if(geteuid() == 0){
 
2251
    
 
2252
    /* Take down the network interface */
 
2253
    if(take_down_interface and geteuid() == 0){
2164
2254
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2165
2255
      if(ret == -1){
2166
2256
        perror_plus("ioctl SIOCGIFFLAGS");
2167
 
      } else if(network.ifr_flags & IFF_UP) {
 
2257
      } else if(network.ifr_flags & IFF_UP){
2168
2258
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2169
2259
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2170
2260
        if(ret == -1){
2175
2265
      if(ret == -1){
2176
2266
        perror_plus("close");
2177
2267
      }
2178
 
      /* Lower privileges permanently */
2179
 
      errno = 0;
2180
 
      ret = setuid(uid);
2181
 
      if(ret == -1){
2182
 
        perror_plus("setuid");
2183
 
      }
2184
2268
    }
2185
2269
  }
 
2270
  /* Lower privileges permanently */
 
2271
  errno = 0;
 
2272
  ret = setuid(uid);
 
2273
  if(ret == -1){
 
2274
    perror_plus("setuid");
 
2275
  }
2186
2276
  
2187
2277
  /* Removes the GPGME temp directory and all files inside */
2188
2278
  if(tempdir_created){
2202
2292
        }
2203
2293
        ret = remove(fullname);
2204
2294
        if(ret == -1){
2205
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2206
 
                  strerror(errno));
 
2295
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2296
                       strerror(errno));
2207
2297
        }
2208
2298
        free(fullname);
2209
2299
      }