/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: Björn Påhlsson
  • Date: 2011-11-14 18:03:35 UTC
  • mto: (505.3.9 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 525.
  • Revision ID: belorn@fukt.bsnet.se-20111114180335-3j4x5mjr7lix2jyj
New convinence error printer: fprintf_plus

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-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
 
76
                                   setgid(), pause() */
77
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
 
#include <grp.h>                /* setgroups() */
91
88
 
92
89
#ifdef __linux__
93
90
#include <sys/klog.h>           /* klogctl() */
111
108
                                   init_gnutls_session(),
112
109
                                   GNUTLS_* */
113
110
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
 
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
113
 
117
114
/* GPGME */
118
115
#include <gpgme.h>              /* All GPGME types, constants and
134
131
const char *argp_program_bug_address = "<mandos@recompile.se>";
135
132
static const char sys_class_net[] = "/sys/class/net";
136
133
char *connect_to = NULL;
137
 
const char *hookdir = HOOKDIR;
138
134
 
139
135
/* Doubly linked list that need to be circularly linked when used */
140
136
typedef struct server{
170
166
 
171
167
/* Function to use when printing errors */
172
168
void perror_plus(const char *print_text){
173
 
  int e = errno;
174
169
  fprintf(stderr, "Mandos plugin %s: ",
175
170
          program_invocation_short_name);
176
 
  errno = e;
177
171
  perror(print_text);
178
172
}
179
173
 
180
 
__attribute__((format (gnu_printf, 2, 3)))
181
174
int fprintf_plus(FILE *stream, const char *format, ...){
182
175
  va_list ap;
183
176
  va_start (ap, format);
184
177
  
185
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
186
 
                             program_invocation_short_name));
 
178
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
187
179
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
188
180
}
189
181
 
193
185
 * "buffer_length" is how much is already used.
194
186
 */
195
187
size_t incbuffer(char **buffer, size_t buffer_length,
196
 
                 size_t buffer_capacity){
 
188
                  size_t buffer_capacity){
197
189
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
198
190
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
199
191
    if(buffer == NULL){
205
197
}
206
198
 
207
199
/* Add server to set of servers to retry periodically */
208
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
209
 
                int af){
 
200
int add_server(const char *ip, uint16_t port,
 
201
                 AvahiIfIndex if_index,
 
202
                 int af){
210
203
  int ret;
211
204
  server *new_server = malloc(sizeof(server));
212
205
  if(new_server == NULL){
213
206
    perror_plus("malloc");
214
 
    return false;
 
207
    return -1;
215
208
  }
216
209
  *new_server = (server){ .ip = strdup(ip),
217
 
                          .port = port,
218
 
                          .if_index = if_index,
219
 
                          .af = af };
 
210
                         .port = port,
 
211
                         .if_index = if_index,
 
212
                         .af = af };
220
213
  if(new_server->ip == NULL){
221
214
    perror_plus("strdup");
222
 
    return false;
 
215
    return -1;
223
216
  }
224
217
  /* Special case of first server */
225
218
  if (mc.current_server == NULL){
236
229
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
237
230
  if(ret == -1){
238
231
    perror_plus("clock_gettime");
239
 
    return false;
 
232
    return -1;
240
233
  }
241
 
  return true;
 
234
  return 0;
242
235
}
243
236
 
244
237
/* 
245
238
 * Initialize GPGME.
246
239
 */
247
 
static bool init_gpgme(const char *seckey, const char *pubkey,
248
 
                       const char *tempdir){
 
240
static bool init_gpgme(const char *seckey,
 
241
                       const char *pubkey, const char *tempdir){
249
242
  gpgme_error_t rc;
250
243
  gpgme_engine_info_t engine_info;
251
244
  
266
259
    
267
260
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
268
261
    if(rc != GPG_ERR_NO_ERROR){
269
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
270
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
262
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
263
              gpgme_strsource(rc), gpgme_strerror(rc));
271
264
      return false;
272
265
    }
273
266
    
274
267
    rc = gpgme_op_import(mc.ctx, pgp_data);
275
268
    if(rc != GPG_ERR_NO_ERROR){
276
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
277
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
269
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
270
              gpgme_strsource(rc), gpgme_strerror(rc));
278
271
      return false;
279
272
    }
280
273
    
287
280
  }
288
281
  
289
282
  if(debug){
290
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
283
    fprintf(stderr, "Initializing GPGME\n");
291
284
  }
292
285
  
293
286
  /* Init GPGME */
294
287
  gpgme_check_version(NULL);
295
288
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
296
289
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
298
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
290
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
291
            gpgme_strsource(rc), gpgme_strerror(rc));
299
292
    return false;
300
293
  }
301
294
  
302
295
  /* Set GPGME home directory for the OpenPGP engine only */
303
296
  rc = gpgme_get_engine_info(&engine_info);
304
297
  if(rc != GPG_ERR_NO_ERROR){
305
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
306
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
298
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
299
            gpgme_strsource(rc), gpgme_strerror(rc));
307
300
    return false;
308
301
  }
309
302
  while(engine_info != NULL){
315
308
    engine_info = engine_info->next;
316
309
  }
317
310
  if(engine_info == NULL){
318
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
319
 
                 tempdir);
 
311
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
320
312
    return false;
321
313
  }
322
314
  
323
315
  /* Create new GPGME "context" */
324
316
  rc = gpgme_new(&(mc.ctx));
325
317
  if(rc != GPG_ERR_NO_ERROR){
326
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
327
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
328
 
                 gpgme_strerror(rc));
 
318
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
319
            gpgme_strsource(rc), gpgme_strerror(rc));
329
320
    return false;
330
321
  }
331
322
  
350
341
  ssize_t plaintext_length = 0;
351
342
  
352
343
  if(debug){
353
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
344
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
354
345
  }
355
346
  
356
347
  /* Create new GPGME data buffer from memory cryptotext */
357
348
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
358
349
                               0);
359
350
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
361
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
351
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
352
            gpgme_strsource(rc), gpgme_strerror(rc));
362
353
    return -1;
363
354
  }
364
355
  
365
356
  /* Create new empty GPGME data buffer for the plaintext */
366
357
  rc = gpgme_data_new(&dh_plain);
367
358
  if(rc != GPG_ERR_NO_ERROR){
368
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
369
 
                 "bad gpgme_data_new: %s: %s\n",
370
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
359
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
360
            gpgme_strsource(rc), gpgme_strerror(rc));
371
361
    gpgme_data_release(dh_crypto);
372
362
    return -1;
373
363
  }
376
366
     data buffer */
377
367
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
378
368
  if(rc != GPG_ERR_NO_ERROR){
379
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
380
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
369
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
370
            gpgme_strsource(rc), gpgme_strerror(rc));
381
371
    plaintext_length = -1;
382
372
    if(debug){
383
373
      gpgme_decrypt_result_t result;
384
374
      result = gpgme_op_decrypt_result(mc.ctx);
385
375
      if(result == NULL){
386
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
376
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
387
377
      } else {
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);
 
378
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
379
                result->unsupported_algorithm);
 
380
        fprintf(stderr, "Wrong key usage: %u\n",
 
381
                result->wrong_key_usage);
392
382
        if(result->file_name != NULL){
393
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
383
          fprintf(stderr, "File name: %s\n", result->file_name);
394
384
        }
395
385
        gpgme_recipient_t recipient;
396
386
        recipient = result->recipients;
397
387
        while(recipient != NULL){
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");
 
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");
405
394
          recipient = recipient->next;
406
395
        }
407
396
      }
410
399
  }
411
400
  
412
401
  if(debug){
413
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
402
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
414
403
  }
415
404
  
416
405
  /* Seek back to the beginning of the GPGME plaintext data buffer */
423
412
  *plaintext = NULL;
424
413
  while(true){
425
414
    plaintext_capacity = incbuffer(plaintext,
426
 
                                   (size_t)plaintext_length,
427
 
                                   plaintext_capacity);
 
415
                                      (size_t)plaintext_length,
 
416
                                      plaintext_capacity);
428
417
    if(plaintext_capacity == 0){
429
 
      perror_plus("incbuffer");
430
 
      plaintext_length = -1;
431
 
      goto decrypt_end;
 
418
        perror_plus("incbuffer");
 
419
        plaintext_length = -1;
 
420
        goto decrypt_end;
432
421
    }
433
422
    
434
423
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
447
436
  }
448
437
  
449
438
  if(debug){
450
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
439
    fprintf(stderr, "Decrypted password is: ");
451
440
    for(ssize_t i = 0; i < plaintext_length; i++){
452
441
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
453
442
    }
475
464
/* GnuTLS log function callback */
476
465
static void debuggnutls(__attribute__((unused)) int level,
477
466
                        const char* string){
478
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
467
  fprintf(stderr, "GnuTLS: %s", string);
479
468
}
480
469
 
481
470
static int init_gnutls_global(const char *pubkeyfilename,
483
472
  int ret;
484
473
  
485
474
  if(debug){
486
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
475
    fprintf(stderr, "Initializing GnuTLS\n");
487
476
  }
488
477
  
489
478
  ret = gnutls_global_init();
490
479
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
492
 
                 safer_gnutls_strerror(ret));
 
480
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
481
            safer_gnutls_strerror(ret));
493
482
    return -1;
494
483
  }
495
484
  
504
493
  /* OpenPGP credentials */
505
494
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
506
495
  if(ret != GNUTLS_E_SUCCESS){
507
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
508
 
                 safer_gnutls_strerror(ret));
 
496
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
497
            safer_gnutls_strerror(ret));
509
498
    gnutls_global_deinit();
510
499
    return -1;
511
500
  }
512
501
  
513
502
  if(debug){
514
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
515
 
                 " secret key %s as GnuTLS credentials\n",
516
 
                 pubkeyfilename,
517
 
                 seckeyfilename);
 
503
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
504
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
505
            seckeyfilename);
518
506
  }
519
507
  
520
508
  ret = gnutls_certificate_set_openpgp_key_file
521
509
    (mc.cred, pubkeyfilename, seckeyfilename,
522
510
     GNUTLS_OPENPGP_FMT_BASE64);
523
511
  if(ret != GNUTLS_E_SUCCESS){
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));
 
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));
529
517
    goto globalfail;
530
518
  }
531
519
  
532
520
  /* GnuTLS server initialization */
533
521
  ret = gnutls_dh_params_init(&mc.dh_params);
534
522
  if(ret != GNUTLS_E_SUCCESS){
535
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
536
 
                 " initialization: %s\n",
537
 
                 safer_gnutls_strerror(ret));
 
523
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
524
            " %s\n", safer_gnutls_strerror(ret));
538
525
    goto globalfail;
539
526
  }
540
527
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
541
528
  if(ret != GNUTLS_E_SUCCESS){
542
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
543
 
                 safer_gnutls_strerror(ret));
 
529
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
530
            safer_gnutls_strerror(ret));
544
531
    goto globalfail;
545
532
  }
546
533
  
566
553
    }
567
554
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
568
555
  if(ret != GNUTLS_E_SUCCESS){
569
 
    fprintf_plus(stderr,
570
 
                 "Error in GnuTLS session initialization: %s\n",
571
 
                 safer_gnutls_strerror(ret));
 
556
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
557
            safer_gnutls_strerror(ret));
572
558
  }
573
559
  
574
560
  {
581
567
      }
582
568
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
583
569
    if(ret != GNUTLS_E_SUCCESS){
584
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
585
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
586
 
                   safer_gnutls_strerror(ret));
 
570
      fprintf(stderr, "Syntax error at: %s\n", err);
 
571
      fprintf(stderr, "GnuTLS error: %s\n",
 
572
              safer_gnutls_strerror(ret));
587
573
      gnutls_deinit(*session);
588
574
      return -1;
589
575
    }
598
584
    }
599
585
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
600
586
  if(ret != GNUTLS_E_SUCCESS){
601
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
602
 
                 safer_gnutls_strerror(ret));
 
587
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
588
            safer_gnutls_strerror(ret));
603
589
    gnutls_deinit(*session);
604
590
    return -1;
605
591
  }
650
636
    pf = PF_INET;
651
637
    break;
652
638
  default:
653
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
639
    fprintf(stderr, "Bad address family: %d\n", af);
654
640
    errno = EINVAL;
655
641
    return -1;
656
642
  }
661
647
  }
662
648
  
663
649
  if(debug){
664
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
665
 
                 PRIu16 "\n", ip, port);
 
650
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
651
            "\n", ip, port);
666
652
  }
667
653
  
668
654
  tcp_sd = socket(pf, SOCK_STREAM, 0);
694
680
  }
695
681
  if(ret == 0){
696
682
    int e = errno;
697
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
683
    fprintf(stderr, "Bad address: %s\n", ip);
698
684
    errno = e;
699
685
    goto mandos_end;
700
686
  }
705
691
    
706
692
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
707
693
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
708
 
                                -Wunreachable-code*/
 
694
                              -Wunreachable-code*/
709
695
      if(if_index == AVAHI_IF_UNSPEC){
710
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
711
 
                     " incomplete without a network interface\n");
 
696
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
697
                " without a network interface\n");
712
698
        errno = EINVAL;
713
699
        goto mandos_end;
714
700
      }
732
718
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
733
719
        perror_plus("if_indextoname");
734
720
      } else {
735
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
736
 
                     "\n", ip, interface, port);
 
721
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
722
                ip, interface, port);
737
723
      }
738
724
    } else {
739
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
740
 
                   ip, port);
 
725
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
726
              port);
741
727
    }
742
728
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
743
729
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
753
739
      perror_plus("inet_ntop");
754
740
    } else {
755
741
      if(strcmp(addrstr, ip) != 0){
756
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
742
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
757
743
      }
758
744
    }
759
745
  }
787
773
  while(true){
788
774
    size_t out_size = strlen(out);
789
775
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
790
 
                                        out_size - written));
 
776
                                   out_size - written));
791
777
    if(ret == -1){
792
778
      int e = errno;
793
779
      perror_plus("write");
813
799
  }
814
800
  
815
801
  if(debug){
816
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
802
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
817
803
  }
818
804
  
819
805
  if(quit_now){
821
807
    goto mandos_end;
822
808
  }
823
809
  
824
 
  /* This casting via intptr_t is to eliminate warning about casting
825
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
826
 
     function "set-session-transport-fd!" does it. */
827
 
  gnutls_transport_set_ptr(session,
828
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
810
  /* Spurious warning from -Wint-to-pointer-cast */
 
811
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
829
812
  
830
813
  if(quit_now){
831
814
    errno = EINTR;
842
825
  
843
826
  if(ret != GNUTLS_E_SUCCESS){
844
827
    if(debug){
845
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
828
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
846
829
      gnutls_perror(ret);
847
830
    }
848
831
    errno = EPROTO;
852
835
  /* Read OpenPGP packet that contains the wanted password */
853
836
  
854
837
  if(debug){
855
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
856
 
                 " %s\n", ip);
 
838
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
839
            ip);
857
840
  }
858
841
  
859
842
  while(true){
864
847
    }
865
848
    
866
849
    buffer_capacity = incbuffer(&buffer, buffer_length,
867
 
                                buffer_capacity);
 
850
                                   buffer_capacity);
868
851
    if(buffer_capacity == 0){
869
852
      int e = errno;
870
853
      perror_plus("incbuffer");
897
880
          }
898
881
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
899
882
        if(ret < 0){
900
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
901
 
                       "***\n");
 
883
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
902
884
          gnutls_perror(ret);
903
885
          errno = EPROTO;
904
886
          goto mandos_end;
905
887
        }
906
888
        break;
907
889
      default:
908
 
        fprintf_plus(stderr, "Unknown error while reading data from"
909
 
                     " encrypted session with Mandos server\n");
 
890
        fprintf(stderr, "Unknown error while reading data from"
 
891
                " encrypted session with Mandos server\n");
910
892
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
911
893
        errno = EIO;
912
894
        goto mandos_end;
917
899
  }
918
900
  
919
901
  if(debug){
920
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
902
    fprintf(stderr, "Closing TLS session\n");
921
903
  }
922
904
  
923
905
  if(quit_now){
935
917
  
936
918
  if(buffer_length > 0){
937
919
    ssize_t decrypted_buffer_size;
938
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
920
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
921
                                               buffer_length,
939
922
                                               &decrypted_buffer);
940
923
    if(decrypted_buffer_size >= 0){
941
924
      
952
935
        if(ret == 0 and ferror(stdout)){
953
936
          int e = errno;
954
937
          if(debug){
955
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
956
 
                         strerror(errno));
 
938
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
939
                    strerror(errno));
957
940
          }
958
941
          errno = e;
959
942
          goto mandos_end;
1016
999
  switch(event){
1017
1000
  default:
1018
1001
  case AVAHI_RESOLVER_FAILURE:
1019
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1020
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1021
 
                 domain,
1022
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
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)));
1023
1005
    break;
1024
1006
    
1025
1007
  case AVAHI_RESOLVER_FOUND:
1027
1009
      char ip[AVAHI_ADDRESS_STR_MAX];
1028
1010
      avahi_address_snprint(ip, sizeof(ip), address);
1029
1011
      if(debug){
1030
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1031
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1032
 
                     host_name, ip, (intmax_t)interface, port);
 
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);
1033
1015
      }
1034
1016
      int ret = start_mandos_communication(ip, port, interface,
1035
1017
                                           avahi_proto_to_af(proto));
1036
1018
      if(ret == 0){
1037
1019
        avahi_simple_poll_quit(mc.simple_poll);
1038
1020
      } else {
1039
 
        if(not add_server(ip, port, interface,
1040
 
                          avahi_proto_to_af(proto))){
1041
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1042
 
                       " list\n", name);
1043
 
        }
 
1021
        ret = add_server(ip, port, interface,
 
1022
                         avahi_proto_to_af(proto));
1044
1023
      }
1045
1024
    }
1046
1025
  }
1070
1049
  default:
1071
1050
  case AVAHI_BROWSER_FAILURE:
1072
1051
    
1073
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1074
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1052
    fprintf(stderr, "(Avahi browser) %s\n",
 
1053
            avahi_strerror(avahi_server_errno(mc.server)));
1075
1054
    avahi_simple_poll_quit(mc.simple_poll);
1076
1055
    return;
1077
1056
    
1084
1063
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1085
1064
                                    name, type, domain, protocol, 0,
1086
1065
                                    resolve_callback, NULL) == NULL)
1087
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1088
 
                   " %s\n", name,
1089
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1066
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1067
              name, avahi_strerror(avahi_server_errno(mc.server)));
1090
1068
    break;
1091
1069
    
1092
1070
  case AVAHI_BROWSER_REMOVE:
1095
1073
  case AVAHI_BROWSER_ALL_FOR_NOW:
1096
1074
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1097
1075
    if(debug){
1098
 
      fprintf_plus(stderr, "No Mandos server found, still"
1099
 
                   " searching...\n");
 
1076
      fprintf(stderr, "No Mandos server found, still searching...\n");
1100
1077
    }
1101
1078
    break;
1102
1079
  }
1141
1118
  /* Reject the loopback device */
1142
1119
  if(ifr->ifr_flags & IFF_LOOPBACK){
1143
1120
    if(debug){
1144
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1145
 
                   ifname);
 
1121
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1122
              ifname);
1146
1123
    }
1147
1124
    return false;
1148
1125
  }
1149
1126
  /* Accept point-to-point devices only if connect_to is specified */
1150
1127
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1151
1128
    if(debug){
1152
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1153
 
                   " \"%s\"\n", ifname);
 
1129
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1130
              ifname);
1154
1131
    }
1155
1132
    return true;
1156
1133
  }
1157
1134
  /* Otherwise, reject non-broadcast-capable devices */
1158
1135
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1159
1136
    if(debug){
1160
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1161
 
                   " \"%s\"\n", ifname);
 
1137
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1138
              ifname);
1162
1139
    }
1163
1140
    return false;
1164
1141
  }
1165
1142
  /* Reject non-ARP interfaces (including dummy interfaces) */
1166
1143
  if(ifr->ifr_flags & IFF_NOARP){
1167
1144
    if(debug){
1168
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1169
 
                   ifname);
 
1145
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1170
1146
    }
1171
1147
    return false;
1172
1148
  }
1173
1149
  
1174
1150
  /* Accept this device */
1175
1151
  if(debug){
1176
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1152
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1177
1153
  }
1178
1154
  return true;
1179
1155
}
1184
1160
 * (This function is passed to scandir(3) as a filter function.)
1185
1161
 */
1186
1162
int good_interface(const struct dirent *if_entry){
 
1163
  int ret;
1187
1164
  if(if_entry->d_name[0] == '.'){
1188
1165
    return 0;
1189
1166
  }
1190
 
  
1191
1167
  struct ifreq ifr;
 
1168
 
1192
1169
  if(not get_flags(if_entry->d_name, &ifr)){
1193
 
    if(debug){
1194
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1195
 
                   "\"%s\"\n", if_entry->d_name);
1196
 
    }
1197
1170
    return 0;
1198
1171
  }
1199
1172
  
1209
1182
 * (This function is passed to scandir(3) as a filter function.)
1210
1183
 */
1211
1184
int up_interface(const struct dirent *if_entry){
 
1185
  ssize_t ssret;
 
1186
  char *flagname = NULL;
1212
1187
  if(if_entry->d_name[0] == '.'){
1213
1188
    return 0;
1214
1189
  }
1215
 
  
1216
 
  struct ifreq ifr;
1217
 
  if(not get_flags(if_entry->d_name, &ifr)){
1218
 
    if(debug){
1219
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1220
 
                   "\"%s\"\n", if_entry->d_name);
1221
 
    }
1222
 
    return 0;
1223
 
  }
1224
 
  
 
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
 
1225
1253
  /* Reject down interfaces */
1226
 
  if(not (ifr.ifr_flags & IFF_UP)){
1227
 
    if(debug){
1228
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1229
 
                   if_entry->d_name);
1230
 
    }
1231
 
    return 0;
1232
 
  }
1233
 
  
1234
 
  /* Reject non-running interfaces */
1235
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1236
 
    if(debug){
1237
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1238
 
                   if_entry->d_name);
1239
 
    }
1240
 
    return 0;
1241
 
  }
1242
 
  
1243
 
  if(not good_flags(if_entry->d_name, &ifr)){
1244
 
    return 0;
 
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);
1245
1286
  }
1246
1287
  return 1;
1247
1288
}
1260
1301
/* Is this directory entry a runnable program? */
1261
1302
int runnable_hook(const struct dirent *direntry){
1262
1303
  int ret;
1263
 
  size_t sret;
1264
1304
  struct stat st;
1265
1305
  
1266
1306
  if((direntry->d_name)[0] == '\0'){
1268
1308
    return 0;
1269
1309
  }
1270
1310
  
1271
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1272
 
                "abcdefghijklmnopqrstuvwxyz"
1273
 
                "0123456789"
1274
 
                "_-");
1275
 
  if((direntry->d_name)[sret] != '\0'){
1276
 
    /* Contains non-allowed characters */
1277
 
    if(debug){
1278
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1279
 
                   direntry->d_name);
1280
 
    }
1281
 
    return 0;
1282
 
  }
1283
 
  
1284
 
  char *fullname = NULL;
1285
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1286
 
  if(ret < 0){
1287
 
    perror_plus("asprintf");
1288
 
    return 0;
1289
 
  }
1290
 
  
1291
 
  ret = stat(fullname, &st);
 
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);
1292
1328
  if(ret == -1){
1293
1329
    if(debug){
1294
 
      perror_plus("Could not stat hook");
 
1330
      perror_plus("Could not stat plugin");
1295
1331
    }
1296
1332
    return 0;
1297
1333
  }
1298
 
  if(not (S_ISREG(st.st_mode))){
 
1334
  if(not (st.st_mode & S_ISREG)){
1299
1335
    /* Not a regular file */
1300
 
    if(debug){
1301
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1302
 
                   direntry->d_name);
1303
 
    }
1304
1336
    return 0;
1305
1337
  }
1306
1338
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1307
1339
    /* Not executable */
1308
 
    if(debug){
1309
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1310
 
                   direntry->d_name);
1311
 
    }
1312
1340
    return 0;
1313
1341
  }
1314
 
  if(debug){
1315
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1316
 
                 direntry->d_name);
1317
 
  }
1318
1342
  return 1;
1319
1343
}
1320
1344
 
1327
1351
  while(true){
1328
1352
    if(mc.current_server == NULL){
1329
1353
      if (debug){
1330
 
        fprintf_plus(stderr, "Wait until first server is found."
1331
 
                     " No timeout!\n");
 
1354
        fprintf(stderr,
 
1355
                "Wait until first server is found. No timeout!\n");
1332
1356
      }
1333
1357
      ret = avahi_simple_poll_iterate(s, -1);
1334
1358
    } else {
1335
1359
      if (debug){
1336
 
        fprintf_plus(stderr, "Check current_server if we should run"
1337
 
                     " it, or wait\n");
 
1360
        fprintf(stderr, "Check current_server if we should run it,"
 
1361
                " or wait\n");
1338
1362
      }
1339
1363
      /* the current time */
1340
1364
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1356
1380
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1357
1381
      
1358
1382
      if (debug){
1359
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1360
 
                     block_time);
 
1383
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1361
1384
      }
1362
1385
      
1363
1386
      if(block_time <= 0){
1383
1406
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1384
1407
    }
1385
1408
    if(ret != 0){
1386
 
      if (ret > 0 or errno != EINTR){
 
1409
      if (ret > 0 or errno != EINTR) {
1387
1410
        return (ret != 1) ? ret : 0;
1388
1411
      }
1389
1412
    }
1390
1413
  }
1391
1414
}
1392
1415
 
1393
 
bool run_network_hooks(const char *mode, const char *interface,
1394
 
                       const float delay){
1395
 
  struct dirent **direntries;
1396
 
  struct dirent *direntry;
1397
 
  int ret;
1398
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1399
 
                         alphasort);
1400
 
  if(numhooks == -1){
1401
 
    perror_plus("scandir");
1402
 
  } else {
1403
 
    int devnull = open("/dev/null", O_RDONLY);
1404
 
    for(int i = 0; i < numhooks; i++){
1405
 
      direntry = direntries[i];
1406
 
      char *fullname = NULL;
1407
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1408
 
      if(ret < 0){
1409
 
        perror_plus("asprintf");
1410
 
        continue;
1411
 
      }
1412
 
      if(debug){
1413
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1414
 
                     direntry->d_name);
1415
 
      }
1416
 
      pid_t hook_pid = fork();
1417
 
      if(hook_pid == 0){
1418
 
        /* Child */
1419
 
        /* Raise privileges */
1420
 
        errno = 0;
1421
 
        ret = seteuid(0);
1422
 
        if(ret == -1){
1423
 
          perror_plus("seteuid");
1424
 
        }
1425
 
        /* Raise privileges even more */
1426
 
        errno = 0;
1427
 
        ret = setuid(0);
1428
 
        if(ret == -1){
1429
 
          perror_plus("setuid");
1430
 
        }
1431
 
        /* Set group */
1432
 
        errno = 0;
1433
 
        ret = setgid(0);
1434
 
        if(ret == -1){
1435
 
          perror_plus("setgid");
1436
 
        }
1437
 
        /* Reset supplementary groups */
1438
 
        errno = 0;
1439
 
        ret = setgroups(0, NULL);
1440
 
        if(ret == -1){
1441
 
          perror_plus("setgroups");
1442
 
        }
1443
 
        dup2(devnull, STDIN_FILENO);
1444
 
        close(devnull);
1445
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1446
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1447
 
        if(ret == -1){
1448
 
          perror_plus("setenv");
1449
 
          _exit(EX_OSERR);
1450
 
        }
1451
 
        ret = setenv("DEVICE", interface, 1);
1452
 
        if(ret == -1){
1453
 
          perror_plus("setenv");
1454
 
          _exit(EX_OSERR);
1455
 
        }
1456
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1457
 
        if(ret == -1){
1458
 
          perror_plus("setenv");
1459
 
          _exit(EX_OSERR);
1460
 
        }
1461
 
        ret = setenv("MODE", mode, 1);
1462
 
        if(ret == -1){
1463
 
          perror_plus("setenv");
1464
 
          _exit(EX_OSERR);
1465
 
        }
1466
 
        char *delaystring;
1467
 
        ret = asprintf(&delaystring, "%f", delay);
1468
 
        if(ret == -1){
1469
 
          perror_plus("asprintf");
1470
 
          _exit(EX_OSERR);
1471
 
        }
1472
 
        ret = setenv("DELAY", delaystring, 1);
1473
 
        if(ret == -1){
1474
 
          free(delaystring);
1475
 
          perror_plus("setenv");
1476
 
          _exit(EX_OSERR);
1477
 
        }
1478
 
        free(delaystring);
1479
 
        if(connect_to != NULL){
1480
 
          ret = setenv("CONNECT", connect_to, 1);
1481
 
          if(ret == -1){
1482
 
            perror_plus("setenv");
1483
 
            _exit(EX_OSERR);
1484
 
          }
1485
 
        }
1486
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1487
 
          perror_plus("execl");
1488
 
          _exit(EXIT_FAILURE);
1489
 
        }
1490
 
      } else {
1491
 
        int status;
1492
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1493
 
          perror_plus("waitpid");
1494
 
          free(fullname);
1495
 
          continue;
1496
 
        }
1497
 
        if(WIFEXITED(status)){
1498
 
          if(WEXITSTATUS(status) != 0){
1499
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1500
 
                         " with status %d\n", direntry->d_name,
1501
 
                         WEXITSTATUS(status));
1502
 
            free(fullname);
1503
 
            continue;
1504
 
          }
1505
 
        } else if(WIFSIGNALED(status)){
1506
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1507
 
                       " signal %d\n", direntry->d_name,
1508
 
                       WTERMSIG(status));
1509
 
          free(fullname);
1510
 
          continue;
1511
 
        } else {
1512
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1513
 
                       " crashed\n", direntry->d_name);
1514
 
          free(fullname);
1515
 
          continue;
1516
 
        }
1517
 
      }
1518
 
      free(fullname);
1519
 
      if(debug){
1520
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1521
 
                     direntry->d_name);
1522
 
      }
1523
 
    }
1524
 
    close(devnull);
1525
 
  }
1526
 
  return true;
1527
 
}
1528
 
 
1529
1416
int main(int argc, char *argv[]){
1530
1417
  AvahiSServiceBrowser *sb = NULL;
1531
1418
  int error;
1611
1498
        .group = 2 },
1612
1499
      { .name = "retry", .key = 132,
1613
1500
        .arg = "SECONDS",
1614
 
        .doc = "Retry interval used when denied by the Mandos server",
1615
 
        .group = 2 },
1616
 
      { .name = "network-hook-dir", .key = 133,
1617
 
        .arg = "DIR",
1618
 
        .doc = "Directory where network hooks are located",
 
1501
        .doc = "Retry interval used when denied by the mandos server",
1619
1502
        .group = 2 },
1620
1503
      /*
1621
1504
       * These reproduce what we would get without ARGP_NO_HELP
1675
1558
          argp_error(state, "Bad retry interval");
1676
1559
        }
1677
1560
        break;
1678
 
      case 133:                 /* --network-hook-dir */
1679
 
        hookdir = arg;
1680
 
        break;
1681
1561
        /*
1682
1562
         * These reproduce what we would get without ARGP_NO_HELP
1683
1563
         */
1689
1569
        argp_state_help(state, state->out_stream,
1690
1570
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1691
1571
      case 'V':                 /* --version */
1692
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1572
        fprintf(state->out_stream, "%s\n", argp_program_version);
1693
1573
        exit(argp_err_exit_status);
1694
1574
        break;
1695
1575
      default:
1722
1602
  {
1723
1603
    /* Work around Debian bug #633582:
1724
1604
       <http://bugs.debian.org/633582> */
 
1605
    struct stat st;
1725
1606
    
1726
1607
    /* Re-raise priviliges */
1727
1608
    errno = 0;
1728
1609
    ret = seteuid(0);
1729
1610
    if(ret == -1){
1730
1611
      perror_plus("seteuid");
1731
 
    } else {
1732
 
      struct stat st;
1733
 
      
1734
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1735
 
        int seckey_fd = open(seckey, O_RDONLY);
1736
 
        if(seckey_fd == -1){
1737
 
          perror_plus("open");
1738
 
        } else {
1739
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1740
 
          if(ret == -1){
1741
 
            perror_plus("fstat");
1742
 
          } else {
1743
 
            if(S_ISREG(st.st_mode)
1744
 
               and st.st_uid == 0 and st.st_gid == 0){
1745
 
              ret = fchown(seckey_fd, uid, gid);
1746
 
              if(ret == -1){
1747
 
                perror_plus("fchown");
1748
 
              }
1749
 
            }
1750
 
          }
1751
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1752
 
        }
1753
 
      }
1754
 
    
1755
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1756
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1757
 
        if(pubkey_fd == -1){
1758
 
          perror_plus("open");
1759
 
        } else {
1760
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1761
 
          if(ret == -1){
1762
 
            perror_plus("fstat");
1763
 
          } else {
1764
 
            if(S_ISREG(st.st_mode)
1765
 
               and st.st_uid == 0 and st.st_gid == 0){
1766
 
              ret = fchown(pubkey_fd, uid, gid);
1767
 
              if(ret == -1){
1768
 
                perror_plus("fchown");
1769
 
              }
1770
 
            }
1771
 
          }
1772
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1773
 
        }
1774
 
      }
1775
 
    
1776
 
      /* Lower privileges */
1777
 
      errno = 0;
1778
 
      ret = seteuid(uid);
1779
 
      if(ret == -1){
1780
 
        perror_plus("seteuid");
1781
 
      }
 
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");
1782
1659
    }
1783
1660
  }
1784
1661
  
1785
 
  /* Run network hooks */
1786
 
  if(not run_network_hooks("start", interface, delay)){
1787
 
    goto end;
 
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);
1788
1697
  }
1789
1698
  
1790
1699
  if(not debug){
1793
1702
  
1794
1703
  if(interface[0] == '\0'){
1795
1704
    struct dirent **direntries;
1796
 
    /* First look for interfaces that are up */
1797
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1705
    ret = scandir(sys_class_net, &direntries, good_interface,
1798
1706
                  alphasort);
1799
 
    if(ret == 0){
1800
 
      /* No up interfaces, look for any good interfaces */
1801
 
      free(direntries);
1802
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1803
 
                    alphasort);
1804
 
    }
1805
1707
    if(ret >= 1){
1806
 
      /* Pick the first interface returned */
 
1708
      /* Pick the first good interface */
1807
1709
      interface = strdup(direntries[0]->d_name);
1808
1710
      if(debug){
1809
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1711
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1810
1712
      }
1811
1713
      if(interface == NULL){
1812
1714
        perror_plus("malloc");
1817
1719
      free(direntries);
1818
1720
    } else {
1819
1721
      free(direntries);
1820
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1722
      fprintf(stderr, "Could not find a network interface\n");
1821
1723
      exitcode = EXIT_FAILURE;
1822
1724
      goto end;
1823
1725
    }
1829
1731
  srand((unsigned int) time(NULL));
1830
1732
  mc.simple_poll = avahi_simple_poll_new();
1831
1733
  if(mc.simple_poll == NULL){
1832
 
    fprintf_plus(stderr,
1833
 
                 "Avahi: Failed to create simple poll object.\n");
 
1734
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1834
1735
    exitcode = EX_UNAVAILABLE;
1835
1736
    goto end;
1836
1737
  }
1902
1803
  if(strcmp(interface, "none") != 0){
1903
1804
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1904
1805
    if(if_index == 0){
1905
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1806
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1906
1807
      exitcode = EX_UNAVAILABLE;
1907
1808
      goto end;
1908
1809
    }
2028
1929
#endif  /* __linux__ */
2029
1930
    /* Lower privileges */
2030
1931
    errno = 0;
2031
 
    /* Lower privileges */
2032
 
    ret = seteuid(uid);
2033
 
    if(ret == -1){
2034
 
      perror_plus("seteuid");
 
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
      }
2035
1944
    }
2036
1945
  }
2037
1946
  
2041
1950
  
2042
1951
  ret = init_gnutls_global(pubkey, seckey);
2043
1952
  if(ret == -1){
2044
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1953
    fprintf(stderr, "init_gnutls_global failed\n");
2045
1954
    exitcode = EX_UNAVAILABLE;
2046
1955
    goto end;
2047
1956
  } else {
2063
1972
  }
2064
1973
  
2065
1974
  if(not init_gpgme(pubkey, seckey, tempdir)){
2066
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1975
    fprintf(stderr, "init_gpgme failed\n");
2067
1976
    exitcode = EX_UNAVAILABLE;
2068
1977
    goto end;
2069
1978
  } else {
2079
1988
    /* (Mainly meant for debugging) */
2080
1989
    char *address = strrchr(connect_to, ':');
2081
1990
    if(address == NULL){
2082
 
      fprintf_plus(stderr, "No colon in address\n");
 
1991
      fprintf(stderr, "No colon in address\n");
2083
1992
      exitcode = EX_USAGE;
2084
1993
      goto end;
2085
1994
    }
2093
2002
    tmpmax = strtoimax(address+1, &tmp, 10);
2094
2003
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2095
2004
       or tmpmax != (uint16_t)tmpmax){
2096
 
      fprintf_plus(stderr, "Bad port number\n");
 
2005
      fprintf(stderr, "Bad port number\n");
2097
2006
      exitcode = EX_USAGE;
2098
2007
      goto end;
2099
2008
    }
2129
2038
        break;
2130
2039
      }
2131
2040
      if(debug){
2132
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2133
 
                     (int)retry_interval);
 
2041
        fprintf(stderr, "Retrying in %d seconds\n",
 
2042
                (int)retry_interval);
2134
2043
      }
2135
2044
      sleep((int)retry_interval);
2136
2045
    }
2166
2075
  
2167
2076
  /* Check if creating the Avahi server object succeeded */
2168
2077
  if(mc.server == NULL){
2169
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2170
 
                 avahi_strerror(error));
 
2078
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2079
            avahi_strerror(error));
2171
2080
    exitcode = EX_UNAVAILABLE;
2172
2081
    goto end;
2173
2082
  }
2181
2090
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2182
2091
                                   NULL, 0, browse_callback, NULL);
2183
2092
  if(sb == NULL){
2184
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2185
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
2093
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2094
            avahi_strerror(avahi_server_errno(mc.server)));
2186
2095
    exitcode = EX_UNAVAILABLE;
2187
2096
    goto end;
2188
2097
  }
2194
2103
  /* Run the main loop */
2195
2104
  
2196
2105
  if(debug){
2197
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2106
    fprintf(stderr, "Starting Avahi loop search\n");
2198
2107
  }
2199
2108
 
2200
2109
  ret = avahi_loop_with_timeout(mc.simple_poll,
2201
2110
                                (int)(retry_interval * 1000));
2202
2111
  if(debug){
2203
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2204
 
                 (ret == 0) ? "successfully" : "with error");
 
2112
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2113
            (ret == 0) ? "successfully" : "with error");
2205
2114
  }
2206
2115
  
2207
2116
 end:
2208
2117
  
2209
2118
  if(debug){
2210
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2119
    fprintf(stderr, "%s exiting\n", argv[0]);
2211
2120
  }
2212
2121
  
2213
2122
  /* Cleanup things */
2229
2138
  if(gpgme_initialized){
2230
2139
    gpgme_release(mc.ctx);
2231
2140
  }
2232
 
  
 
2141
 
2233
2142
  /* Cleans up the circular linked list of Mandos servers the client
2234
2143
     has seen */
2235
2144
  if(mc.current_server != NULL){
2241
2150
    }
2242
2151
  }
2243
2152
  
2244
 
  /* Run network hooks */
2245
 
  run_network_hooks("stop", interface, delay);
 
2153
  /* XXX run network hooks "stop" here  */
2246
2154
  
2247
 
  /* Re-raise priviliges */
2248
 
  {
 
2155
  /* Take down the network interface */
 
2156
  if(take_down_interface){
 
2157
    /* Re-raise priviliges */
2249
2158
    errno = 0;
2250
2159
    ret = seteuid(0);
2251
2160
    if(ret == -1){
2252
2161
      perror_plus("seteuid");
2253
2162
    }
2254
 
    
2255
 
    /* Take down the network interface */
2256
 
    if(take_down_interface and geteuid() == 0){
 
2163
    if(geteuid() == 0){
2257
2164
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2258
2165
      if(ret == -1){
2259
2166
        perror_plus("ioctl SIOCGIFFLAGS");
2260
 
      } else if(network.ifr_flags & IFF_UP){
 
2167
      } else if(network.ifr_flags & IFF_UP) {
2261
2168
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2262
2169
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2263
2170
        if(ret == -1){
2268
2175
      if(ret == -1){
2269
2176
        perror_plus("close");
2270
2177
      }
 
2178
      /* Lower privileges permanently */
 
2179
      errno = 0;
 
2180
      ret = setuid(uid);
 
2181
      if(ret == -1){
 
2182
        perror_plus("setuid");
 
2183
      }
2271
2184
    }
2272
2185
  }
2273
 
  /* Lower privileges permanently */
2274
 
  errno = 0;
2275
 
  ret = setuid(uid);
2276
 
  if(ret == -1){
2277
 
    perror_plus("setuid");
2278
 
  }
2279
2186
  
2280
2187
  /* Removes the GPGME temp directory and all files inside */
2281
2188
  if(tempdir_created){
2295
2202
        }
2296
2203
        ret = remove(fullname);
2297
2204
        if(ret == -1){
2298
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2299
 
                       strerror(errno));
 
2205
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2206
                  strerror(errno));
2300
2207
        }
2301
2208
        free(fullname);
2302
2209
      }