/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
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){
839
825
  
840
826
  if(ret != GNUTLS_E_SUCCESS){
841
827
    if(debug){
842
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
828
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
843
829
      gnutls_perror(ret);
844
830
    }
845
831
    errno = EPROTO;
849
835
  /* Read OpenPGP packet that contains the wanted password */
850
836
  
851
837
  if(debug){
852
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
853
 
                 " %s\n", ip);
 
838
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
839
            ip);
854
840
  }
855
841
  
856
842
  while(true){
861
847
    }
862
848
    
863
849
    buffer_capacity = incbuffer(&buffer, buffer_length,
864
 
                                buffer_capacity);
 
850
                                   buffer_capacity);
865
851
    if(buffer_capacity == 0){
866
852
      int e = errno;
867
853
      perror_plus("incbuffer");
894
880
          }
895
881
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
896
882
        if(ret < 0){
897
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
898
 
                       "***\n");
 
883
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
899
884
          gnutls_perror(ret);
900
885
          errno = EPROTO;
901
886
          goto mandos_end;
902
887
        }
903
888
        break;
904
889
      default:
905
 
        fprintf_plus(stderr, "Unknown error while reading data from"
906
 
                     " encrypted session with Mandos server\n");
 
890
        fprintf(stderr, "Unknown error while reading data from"
 
891
                " encrypted session with Mandos server\n");
907
892
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
908
893
        errno = EIO;
909
894
        goto mandos_end;
914
899
  }
915
900
  
916
901
  if(debug){
917
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
902
    fprintf(stderr, "Closing TLS session\n");
918
903
  }
919
904
  
920
905
  if(quit_now){
932
917
  
933
918
  if(buffer_length > 0){
934
919
    ssize_t decrypted_buffer_size;
935
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
920
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
921
                                               buffer_length,
936
922
                                               &decrypted_buffer);
937
923
    if(decrypted_buffer_size >= 0){
938
924
      
949
935
        if(ret == 0 and ferror(stdout)){
950
936
          int e = errno;
951
937
          if(debug){
952
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
953
 
                         strerror(errno));
 
938
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
939
                    strerror(errno));
954
940
          }
955
941
          errno = e;
956
942
          goto mandos_end;
1013
999
  switch(event){
1014
1000
  default:
1015
1001
  case AVAHI_RESOLVER_FAILURE:
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)));
 
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)));
1020
1005
    break;
1021
1006
    
1022
1007
  case AVAHI_RESOLVER_FOUND:
1024
1009
      char ip[AVAHI_ADDRESS_STR_MAX];
1025
1010
      avahi_address_snprint(ip, sizeof(ip), address);
1026
1011
      if(debug){
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);
 
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);
1030
1015
      }
1031
1016
      int ret = start_mandos_communication(ip, port, interface,
1032
1017
                                           avahi_proto_to_af(proto));
1033
1018
      if(ret == 0){
1034
1019
        avahi_simple_poll_quit(mc.simple_poll);
1035
1020
      } else {
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
 
        }
 
1021
        ret = add_server(ip, port, interface,
 
1022
                         avahi_proto_to_af(proto));
1041
1023
      }
1042
1024
    }
1043
1025
  }
1067
1049
  default:
1068
1050
  case AVAHI_BROWSER_FAILURE:
1069
1051
    
1070
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1071
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1052
    fprintf(stderr, "(Avahi browser) %s\n",
 
1053
            avahi_strerror(avahi_server_errno(mc.server)));
1072
1054
    avahi_simple_poll_quit(mc.simple_poll);
1073
1055
    return;
1074
1056
    
1081
1063
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1082
1064
                                    name, type, domain, protocol, 0,
1083
1065
                                    resolve_callback, NULL) == NULL)
1084
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1085
 
                   " %s\n", name,
1086
 
                   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)));
1087
1068
    break;
1088
1069
    
1089
1070
  case AVAHI_BROWSER_REMOVE:
1092
1073
  case AVAHI_BROWSER_ALL_FOR_NOW:
1093
1074
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1094
1075
    if(debug){
1095
 
      fprintf_plus(stderr, "No Mandos server found, still"
1096
 
                   " searching...\n");
 
1076
      fprintf(stderr, "No Mandos server found, still searching...\n");
1097
1077
    }
1098
1078
    break;
1099
1079
  }
1138
1118
  /* Reject the loopback device */
1139
1119
  if(ifr->ifr_flags & IFF_LOOPBACK){
1140
1120
    if(debug){
1141
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1142
 
                   ifname);
 
1121
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1122
              ifname);
1143
1123
    }
1144
1124
    return false;
1145
1125
  }
1146
1126
  /* Accept point-to-point devices only if connect_to is specified */
1147
1127
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1148
1128
    if(debug){
1149
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1150
 
                   " \"%s\"\n", ifname);
 
1129
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1130
              ifname);
1151
1131
    }
1152
1132
    return true;
1153
1133
  }
1154
1134
  /* Otherwise, reject non-broadcast-capable devices */
1155
1135
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1156
1136
    if(debug){
1157
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1158
 
                   " \"%s\"\n", ifname);
 
1137
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1138
              ifname);
1159
1139
    }
1160
1140
    return false;
1161
1141
  }
1162
1142
  /* Reject non-ARP interfaces (including dummy interfaces) */
1163
1143
  if(ifr->ifr_flags & IFF_NOARP){
1164
1144
    if(debug){
1165
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1166
 
                   ifname);
 
1145
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1167
1146
    }
1168
1147
    return false;
1169
1148
  }
1170
1149
  
1171
1150
  /* Accept this device */
1172
1151
  if(debug){
1173
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1152
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
1174
1153
  }
1175
1154
  return true;
1176
1155
}
1181
1160
 * (This function is passed to scandir(3) as a filter function.)
1182
1161
 */
1183
1162
int good_interface(const struct dirent *if_entry){
 
1163
  int ret;
1184
1164
  if(if_entry->d_name[0] == '.'){
1185
1165
    return 0;
1186
1166
  }
1187
 
  
1188
1167
  struct ifreq ifr;
 
1168
 
1189
1169
  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
 
    }
1194
1170
    return 0;
1195
1171
  }
1196
1172
  
1206
1182
 * (This function is passed to scandir(3) as a filter function.)
1207
1183
 */
1208
1184
int up_interface(const struct dirent *if_entry){
 
1185
  ssize_t ssret;
 
1186
  char *flagname = NULL;
1209
1187
  if(if_entry->d_name[0] == '.'){
1210
1188
    return 0;
1211
1189
  }
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
 
  
 
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
 
1222
1253
  /* Reject down interfaces */
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;
 
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);
1242
1286
  }
1243
1287
  return 1;
1244
1288
}
1257
1301
/* Is this directory entry a runnable program? */
1258
1302
int runnable_hook(const struct dirent *direntry){
1259
1303
  int ret;
1260
 
  size_t sret;
1261
1304
  struct stat st;
1262
1305
  
1263
1306
  if((direntry->d_name)[0] == '\0'){
1265
1308
    return 0;
1266
1309
  }
1267
1310
  
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);
 
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);
1289
1328
  if(ret == -1){
1290
1329
    if(debug){
1291
 
      perror_plus("Could not stat hook");
 
1330
      perror_plus("Could not stat plugin");
1292
1331
    }
1293
1332
    return 0;
1294
1333
  }
1295
 
  if(not (S_ISREG(st.st_mode))){
 
1334
  if(not (st.st_mode & S_ISREG)){
1296
1335
    /* Not a regular file */
1297
 
    if(debug){
1298
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1299
 
                   direntry->d_name);
1300
 
    }
1301
1336
    return 0;
1302
1337
  }
1303
1338
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1304
1339
    /* Not executable */
1305
 
    if(debug){
1306
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1307
 
                   direntry->d_name);
1308
 
    }
1309
1340
    return 0;
1310
1341
  }
1311
 
  if(debug){
1312
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1313
 
                 direntry->d_name);
1314
 
  }
1315
1342
  return 1;
1316
1343
}
1317
1344
 
1324
1351
  while(true){
1325
1352
    if(mc.current_server == NULL){
1326
1353
      if (debug){
1327
 
        fprintf_plus(stderr, "Wait until first server is found."
1328
 
                     " No timeout!\n");
 
1354
        fprintf(stderr,
 
1355
                "Wait until first server is found. No timeout!\n");
1329
1356
      }
1330
1357
      ret = avahi_simple_poll_iterate(s, -1);
1331
1358
    } else {
1332
1359
      if (debug){
1333
 
        fprintf_plus(stderr, "Check current_server if we should run"
1334
 
                     " it, or wait\n");
 
1360
        fprintf(stderr, "Check current_server if we should run it,"
 
1361
                " or wait\n");
1335
1362
      }
1336
1363
      /* the current time */
1337
1364
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1353
1380
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1354
1381
      
1355
1382
      if (debug){
1356
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1357
 
                     block_time);
 
1383
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1358
1384
      }
1359
1385
      
1360
1386
      if(block_time <= 0){
1380
1406
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1381
1407
    }
1382
1408
    if(ret != 0){
1383
 
      if (ret > 0 or errno != EINTR){
 
1409
      if (ret > 0 or errno != EINTR) {
1384
1410
        return (ret != 1) ? ret : 0;
1385
1411
      }
1386
1412
    }
1387
1413
  }
1388
1414
}
1389
1415
 
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
 
 
1526
1416
int main(int argc, char *argv[]){
1527
1417
  AvahiSServiceBrowser *sb = NULL;
1528
1418
  int error;
1608
1498
        .group = 2 },
1609
1499
      { .name = "retry", .key = 132,
1610
1500
        .arg = "SECONDS",
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",
 
1501
        .doc = "Retry interval used when denied by the mandos server",
1616
1502
        .group = 2 },
1617
1503
      /*
1618
1504
       * These reproduce what we would get without ARGP_NO_HELP
1672
1558
          argp_error(state, "Bad retry interval");
1673
1559
        }
1674
1560
        break;
1675
 
      case 133:                 /* --network-hook-dir */
1676
 
        hookdir = arg;
1677
 
        break;
1678
1561
        /*
1679
1562
         * These reproduce what we would get without ARGP_NO_HELP
1680
1563
         */
1686
1569
        argp_state_help(state, state->out_stream,
1687
1570
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1688
1571
      case 'V':                 /* --version */
1689
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1572
        fprintf(state->out_stream, "%s\n", argp_program_version);
1690
1573
        exit(argp_err_exit_status);
1691
1574
        break;
1692
1575
      default:
1719
1602
  {
1720
1603
    /* Work around Debian bug #633582:
1721
1604
       <http://bugs.debian.org/633582> */
 
1605
    struct stat st;
1722
1606
    
1723
1607
    /* Re-raise priviliges */
1724
1608
    errno = 0;
1725
1609
    ret = seteuid(0);
1726
1610
    if(ret == -1){
1727
1611
      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
 
      }
 
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");
1779
1659
    }
1780
1660
  }
1781
1661
  
1782
 
  /* Run network hooks */
1783
 
  if(not run_network_hooks("start", interface, delay)){
1784
 
    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);
1785
1697
  }
1786
1698
  
1787
1699
  if(not debug){
1790
1702
  
1791
1703
  if(interface[0] == '\0'){
1792
1704
    struct dirent **direntries;
1793
 
    /* First look for interfaces that are up */
1794
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1705
    ret = scandir(sys_class_net, &direntries, good_interface,
1795
1706
                  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
 
    }
1802
1707
    if(ret >= 1){
1803
 
      /* Pick the first interface returned */
 
1708
      /* Pick the first good interface */
1804
1709
      interface = strdup(direntries[0]->d_name);
1805
1710
      if(debug){
1806
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1711
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1807
1712
      }
1808
1713
      if(interface == NULL){
1809
1714
        perror_plus("malloc");
1814
1719
      free(direntries);
1815
1720
    } else {
1816
1721
      free(direntries);
1817
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1722
      fprintf(stderr, "Could not find a network interface\n");
1818
1723
      exitcode = EXIT_FAILURE;
1819
1724
      goto end;
1820
1725
    }
1826
1731
  srand((unsigned int) time(NULL));
1827
1732
  mc.simple_poll = avahi_simple_poll_new();
1828
1733
  if(mc.simple_poll == NULL){
1829
 
    fprintf_plus(stderr,
1830
 
                 "Avahi: Failed to create simple poll object.\n");
 
1734
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1831
1735
    exitcode = EX_UNAVAILABLE;
1832
1736
    goto end;
1833
1737
  }
1899
1803
  if(strcmp(interface, "none") != 0){
1900
1804
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1901
1805
    if(if_index == 0){
1902
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1806
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1903
1807
      exitcode = EX_UNAVAILABLE;
1904
1808
      goto end;
1905
1809
    }
2025
1929
#endif  /* __linux__ */
2026
1930
    /* Lower privileges */
2027
1931
    errno = 0;
2028
 
    /* Lower privileges */
2029
 
    ret = seteuid(uid);
2030
 
    if(ret == -1){
2031
 
      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
      }
2032
1944
    }
2033
1945
  }
2034
1946
  
2038
1950
  
2039
1951
  ret = init_gnutls_global(pubkey, seckey);
2040
1952
  if(ret == -1){
2041
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1953
    fprintf(stderr, "init_gnutls_global failed\n");
2042
1954
    exitcode = EX_UNAVAILABLE;
2043
1955
    goto end;
2044
1956
  } else {
2060
1972
  }
2061
1973
  
2062
1974
  if(not init_gpgme(pubkey, seckey, tempdir)){
2063
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1975
    fprintf(stderr, "init_gpgme failed\n");
2064
1976
    exitcode = EX_UNAVAILABLE;
2065
1977
    goto end;
2066
1978
  } else {
2076
1988
    /* (Mainly meant for debugging) */
2077
1989
    char *address = strrchr(connect_to, ':');
2078
1990
    if(address == NULL){
2079
 
      fprintf_plus(stderr, "No colon in address\n");
 
1991
      fprintf(stderr, "No colon in address\n");
2080
1992
      exitcode = EX_USAGE;
2081
1993
      goto end;
2082
1994
    }
2090
2002
    tmpmax = strtoimax(address+1, &tmp, 10);
2091
2003
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2092
2004
       or tmpmax != (uint16_t)tmpmax){
2093
 
      fprintf_plus(stderr, "Bad port number\n");
 
2005
      fprintf(stderr, "Bad port number\n");
2094
2006
      exitcode = EX_USAGE;
2095
2007
      goto end;
2096
2008
    }
2126
2038
        break;
2127
2039
      }
2128
2040
      if(debug){
2129
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2130
 
                     (int)retry_interval);
 
2041
        fprintf(stderr, "Retrying in %d seconds\n",
 
2042
                (int)retry_interval);
2131
2043
      }
2132
2044
      sleep((int)retry_interval);
2133
2045
    }
2163
2075
  
2164
2076
  /* Check if creating the Avahi server object succeeded */
2165
2077
  if(mc.server == NULL){
2166
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2167
 
                 avahi_strerror(error));
 
2078
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2079
            avahi_strerror(error));
2168
2080
    exitcode = EX_UNAVAILABLE;
2169
2081
    goto end;
2170
2082
  }
2178
2090
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2179
2091
                                   NULL, 0, browse_callback, NULL);
2180
2092
  if(sb == NULL){
2181
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2182
 
                 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)));
2183
2095
    exitcode = EX_UNAVAILABLE;
2184
2096
    goto end;
2185
2097
  }
2191
2103
  /* Run the main loop */
2192
2104
  
2193
2105
  if(debug){
2194
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
2106
    fprintf(stderr, "Starting Avahi loop search\n");
2195
2107
  }
2196
2108
 
2197
2109
  ret = avahi_loop_with_timeout(mc.simple_poll,
2198
2110
                                (int)(retry_interval * 1000));
2199
2111
  if(debug){
2200
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2201
 
                 (ret == 0) ? "successfully" : "with error");
 
2112
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2113
            (ret == 0) ? "successfully" : "with error");
2202
2114
  }
2203
2115
  
2204
2116
 end:
2205
2117
  
2206
2118
  if(debug){
2207
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
2119
    fprintf(stderr, "%s exiting\n", argv[0]);
2208
2120
  }
2209
2121
  
2210
2122
  /* Cleanup things */
2226
2138
  if(gpgme_initialized){
2227
2139
    gpgme_release(mc.ctx);
2228
2140
  }
2229
 
  
 
2141
 
2230
2142
  /* Cleans up the circular linked list of Mandos servers the client
2231
2143
     has seen */
2232
2144
  if(mc.current_server != NULL){
2238
2150
    }
2239
2151
  }
2240
2152
  
2241
 
  /* Run network hooks */
2242
 
  run_network_hooks("stop", interface, delay);
 
2153
  /* XXX run network hooks "stop" here  */
2243
2154
  
2244
 
  /* Re-raise priviliges */
2245
 
  {
 
2155
  /* Take down the network interface */
 
2156
  if(take_down_interface){
 
2157
    /* Re-raise priviliges */
2246
2158
    errno = 0;
2247
2159
    ret = seteuid(0);
2248
2160
    if(ret == -1){
2249
2161
      perror_plus("seteuid");
2250
2162
    }
2251
 
    
2252
 
    /* Take down the network interface */
2253
 
    if(take_down_interface and geteuid() == 0){
 
2163
    if(geteuid() == 0){
2254
2164
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2255
2165
      if(ret == -1){
2256
2166
        perror_plus("ioctl SIOCGIFFLAGS");
2257
 
      } else if(network.ifr_flags & IFF_UP){
 
2167
      } else if(network.ifr_flags & IFF_UP) {
2258
2168
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2259
2169
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2260
2170
        if(ret == -1){
2265
2175
      if(ret == -1){
2266
2176
        perror_plus("close");
2267
2177
      }
 
2178
      /* Lower privileges permanently */
 
2179
      errno = 0;
 
2180
      ret = setuid(uid);
 
2181
      if(ret == -1){
 
2182
        perror_plus("setuid");
 
2183
      }
2268
2184
    }
2269
2185
  }
2270
 
  /* Lower privileges permanently */
2271
 
  errno = 0;
2272
 
  ret = setuid(uid);
2273
 
  if(ret == -1){
2274
 
    perror_plus("setuid");
2275
 
  }
2276
2186
  
2277
2187
  /* Removes the GPGME temp directory and all files inside */
2278
2188
  if(tempdir_created){
2292
2202
        }
2293
2203
        ret = remove(fullname);
2294
2204
        if(ret == -1){
2295
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2296
 
                       strerror(errno));
 
2205
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2206
                  strerror(errno));
2297
2207
        }
2298
2208
        free(fullname);
2299
2209
      }