/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

* plugins.d/mandos-client.c (main): Add "DELAY" environment variable.
                                    Check return value from setenv().

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