/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2012-06-09 23:41:07 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120609234107-vm6zilzz0y6aihsm
* plugins.d/mandos-client.c (raise_privileges,
  raise_privileges_permanently, lower_privileges): Return error_t and
                                                   save old errno
                                                   before calling any
                                                   other function.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2012 Teddy Hogeborn
 
13
 * Copyright © 2008-2012 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
 
76
                                   setgid(), pause(), _exit() */
77
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
#include <grp.h>                /* setgroups() */
88
91
 
89
92
#ifdef __linux__
90
93
#include <sys/klog.h>           /* klogctl() */
108
111
                                   init_gnutls_session(),
109
112
                                   GNUTLS_* */
110
113
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
114
                         /* gnutls_certificate_set_openpgp_key_file(),
 
115
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
116
 
114
117
/* GPGME */
115
118
#include <gpgme.h>              /* All GPGME types, constants and
123
126
#define PATHDIR "/conf/conf.d/mandos"
124
127
#define SECKEY "seckey.txt"
125
128
#define PUBKEY "pubkey.txt"
 
129
#define HOOKDIR "/lib/mandos/network-hooks.d"
126
130
 
127
131
bool debug = false;
128
132
static const char mandos_protocol_version[] = "1";
130
134
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
135
static const char sys_class_net[] = "/sys/class/net";
132
136
char *connect_to = NULL;
 
137
const char *hookdir = HOOKDIR;
 
138
uid_t uid = 65534;
 
139
gid_t gid = 65534;
133
140
 
134
141
/* Doubly linked list that need to be circularly linked when used */
135
142
typedef struct server{
165
172
 
166
173
/* Function to use when printing errors */
167
174
void perror_plus(const char *print_text){
 
175
  int e = errno;
168
176
  fprintf(stderr, "Mandos plugin %s: ",
169
177
          program_invocation_short_name);
 
178
  errno = e;
170
179
  perror(print_text);
171
180
}
172
181
 
 
182
__attribute__((format (gnu_printf, 2, 3)))
 
183
int fprintf_plus(FILE *stream, const char *format, ...){
 
184
  va_list ap;
 
185
  va_start (ap, format);
 
186
  
 
187
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
188
                             program_invocation_short_name));
 
189
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
190
}
 
191
 
173
192
/*
174
193
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
194
 * bytes. "buffer_capacity" is how much is currently allocated,
176
195
 * "buffer_length" is how much is already used.
177
196
 */
178
197
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
198
                 size_t buffer_capacity){
180
199
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
200
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
201
    if(buffer == NULL){
188
207
}
189
208
 
190
209
/* Add server to set of servers to retry periodically */
191
 
int add_server(const char *ip, uint16_t port,
192
 
                 AvahiIfIndex if_index,
193
 
                 int af){
 
210
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
211
                int af){
194
212
  int ret;
195
213
  server *new_server = malloc(sizeof(server));
196
214
  if(new_server == NULL){
197
215
    perror_plus("malloc");
198
 
    return -1;
 
216
    return false;
199
217
  }
200
218
  *new_server = (server){ .ip = strdup(ip),
201
 
                         .port = port,
202
 
                         .if_index = if_index,
203
 
                         .af = af };
 
219
                          .port = port,
 
220
                          .if_index = if_index,
 
221
                          .af = af };
204
222
  if(new_server->ip == NULL){
205
223
    perror_plus("strdup");
206
 
    return -1;
 
224
    return false;
207
225
  }
208
226
  /* Special case of first server */
209
227
  if (mc.current_server == NULL){
220
238
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
221
239
  if(ret == -1){
222
240
    perror_plus("clock_gettime");
223
 
    return -1;
 
241
    return false;
224
242
  }
225
 
  return 0;
 
243
  return true;
226
244
}
227
245
 
228
246
/* 
229
247
 * Initialize GPGME.
230
248
 */
231
 
static bool init_gpgme(const char *seckey,
232
 
                       const char *pubkey, const char *tempdir){
 
249
static bool init_gpgme(const char *seckey, const char *pubkey,
 
250
                       const char *tempdir){
233
251
  gpgme_error_t rc;
234
252
  gpgme_engine_info_t engine_info;
235
253
  
250
268
    
251
269
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
252
270
    if(rc != GPG_ERR_NO_ERROR){
253
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
254
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
271
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
272
                   gpgme_strsource(rc), gpgme_strerror(rc));
255
273
      return false;
256
274
    }
257
275
    
258
276
    rc = gpgme_op_import(mc.ctx, pgp_data);
259
277
    if(rc != GPG_ERR_NO_ERROR){
260
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
261
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
262
280
      return false;
263
281
    }
264
282
    
271
289
  }
272
290
  
273
291
  if(debug){
274
 
    fprintf(stderr, "Initializing GPGME\n");
 
292
    fprintf_plus(stderr, "Initializing GPGME\n");
275
293
  }
276
294
  
277
295
  /* Init GPGME */
278
296
  gpgme_check_version(NULL);
279
297
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
280
298
  if(rc != GPG_ERR_NO_ERROR){
281
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
282
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
299
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
300
                 gpgme_strsource(rc), gpgme_strerror(rc));
283
301
    return false;
284
302
  }
285
303
  
286
304
  /* Set GPGME home directory for the OpenPGP engine only */
287
305
  rc = gpgme_get_engine_info(&engine_info);
288
306
  if(rc != GPG_ERR_NO_ERROR){
289
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
290
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
307
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
308
                 gpgme_strsource(rc), gpgme_strerror(rc));
291
309
    return false;
292
310
  }
293
311
  while(engine_info != NULL){
299
317
    engine_info = engine_info->next;
300
318
  }
301
319
  if(engine_info == NULL){
302
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
320
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
321
                 tempdir);
303
322
    return false;
304
323
  }
305
324
  
306
325
  /* Create new GPGME "context" */
307
326
  rc = gpgme_new(&(mc.ctx));
308
327
  if(rc != GPG_ERR_NO_ERROR){
309
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
310
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
328
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
329
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
330
                 gpgme_strerror(rc));
311
331
    return false;
312
332
  }
313
333
  
332
352
  ssize_t plaintext_length = 0;
333
353
  
334
354
  if(debug){
335
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
355
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
336
356
  }
337
357
  
338
358
  /* Create new GPGME data buffer from memory cryptotext */
339
359
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
340
360
                               0);
341
361
  if(rc != GPG_ERR_NO_ERROR){
342
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
343
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
362
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
363
                 gpgme_strsource(rc), gpgme_strerror(rc));
344
364
    return -1;
345
365
  }
346
366
  
347
367
  /* Create new empty GPGME data buffer for the plaintext */
348
368
  rc = gpgme_data_new(&dh_plain);
349
369
  if(rc != GPG_ERR_NO_ERROR){
350
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
351
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
370
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
371
                 "bad gpgme_data_new: %s: %s\n",
 
372
                 gpgme_strsource(rc), gpgme_strerror(rc));
352
373
    gpgme_data_release(dh_crypto);
353
374
    return -1;
354
375
  }
357
378
     data buffer */
358
379
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
359
380
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
361
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
381
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
382
                 gpgme_strsource(rc), gpgme_strerror(rc));
362
383
    plaintext_length = -1;
363
384
    if(debug){
364
385
      gpgme_decrypt_result_t result;
365
386
      result = gpgme_op_decrypt_result(mc.ctx);
366
387
      if(result == NULL){
367
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
388
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
368
389
      } else {
369
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
370
 
                result->unsupported_algorithm);
371
 
        fprintf(stderr, "Wrong key usage: %u\n",
372
 
                result->wrong_key_usage);
 
390
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
391
                     result->unsupported_algorithm);
 
392
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
393
                     result->wrong_key_usage);
373
394
        if(result->file_name != NULL){
374
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
395
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
375
396
        }
376
397
        gpgme_recipient_t recipient;
377
398
        recipient = result->recipients;
378
399
        while(recipient != NULL){
379
 
          fprintf(stderr, "Public key algorithm: %s\n",
380
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
381
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
382
 
          fprintf(stderr, "Secret key available: %s\n",
383
 
                  recipient->status == GPG_ERR_NO_SECKEY
384
 
                  ? "No" : "Yes");
 
400
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
401
                       gpgme_pubkey_algo_name
 
402
                       (recipient->pubkey_algo));
 
403
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
404
          fprintf_plus(stderr, "Secret key available: %s\n",
 
405
                       recipient->status == GPG_ERR_NO_SECKEY
 
406
                       ? "No" : "Yes");
385
407
          recipient = recipient->next;
386
408
        }
387
409
      }
390
412
  }
391
413
  
392
414
  if(debug){
393
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
415
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
394
416
  }
395
417
  
396
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
403
425
  *plaintext = NULL;
404
426
  while(true){
405
427
    plaintext_capacity = incbuffer(plaintext,
406
 
                                      (size_t)plaintext_length,
407
 
                                      plaintext_capacity);
 
428
                                   (size_t)plaintext_length,
 
429
                                   plaintext_capacity);
408
430
    if(plaintext_capacity == 0){
409
 
        perror_plus("incbuffer");
410
 
        plaintext_length = -1;
411
 
        goto decrypt_end;
 
431
      perror_plus("incbuffer");
 
432
      plaintext_length = -1;
 
433
      goto decrypt_end;
412
434
    }
413
435
    
414
436
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
427
449
  }
428
450
  
429
451
  if(debug){
430
 
    fprintf(stderr, "Decrypted password is: ");
 
452
    fprintf_plus(stderr, "Decrypted password is: ");
431
453
    for(ssize_t i = 0; i < plaintext_length; i++){
432
454
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
433
455
    }
455
477
/* GnuTLS log function callback */
456
478
static void debuggnutls(__attribute__((unused)) int level,
457
479
                        const char* string){
458
 
  fprintf(stderr, "GnuTLS: %s", string);
 
480
  fprintf_plus(stderr, "GnuTLS: %s", string);
459
481
}
460
482
 
461
483
static int init_gnutls_global(const char *pubkeyfilename,
463
485
  int ret;
464
486
  
465
487
  if(debug){
466
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
488
    fprintf_plus(stderr, "Initializing GnuTLS\n");
467
489
  }
468
490
  
469
491
  ret = gnutls_global_init();
470
492
  if(ret != GNUTLS_E_SUCCESS){
471
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
472
 
            safer_gnutls_strerror(ret));
 
493
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
494
                 safer_gnutls_strerror(ret));
473
495
    return -1;
474
496
  }
475
497
  
484
506
  /* OpenPGP credentials */
485
507
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
486
508
  if(ret != GNUTLS_E_SUCCESS){
487
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
488
 
            safer_gnutls_strerror(ret));
 
509
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
510
                 safer_gnutls_strerror(ret));
489
511
    gnutls_global_deinit();
490
512
    return -1;
491
513
  }
492
514
  
493
515
  if(debug){
494
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
495
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
496
 
            seckeyfilename);
 
516
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
517
                 " secret key %s as GnuTLS credentials\n",
 
518
                 pubkeyfilename,
 
519
                 seckeyfilename);
497
520
  }
498
521
  
499
522
  ret = gnutls_certificate_set_openpgp_key_file
500
523
    (mc.cred, pubkeyfilename, seckeyfilename,
501
524
     GNUTLS_OPENPGP_FMT_BASE64);
502
525
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf(stderr,
504
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
505
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
506
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
507
 
            safer_gnutls_strerror(ret));
 
526
    fprintf_plus(stderr,
 
527
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
528
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
529
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
530
                 safer_gnutls_strerror(ret));
508
531
    goto globalfail;
509
532
  }
510
533
  
511
534
  /* GnuTLS server initialization */
512
535
  ret = gnutls_dh_params_init(&mc.dh_params);
513
536
  if(ret != GNUTLS_E_SUCCESS){
514
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
515
 
            " %s\n", safer_gnutls_strerror(ret));
 
537
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
538
                 " initialization: %s\n",
 
539
                 safer_gnutls_strerror(ret));
516
540
    goto globalfail;
517
541
  }
518
542
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
519
543
  if(ret != GNUTLS_E_SUCCESS){
520
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
521
 
            safer_gnutls_strerror(ret));
 
544
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
545
                 safer_gnutls_strerror(ret));
522
546
    goto globalfail;
523
547
  }
524
548
  
544
568
    }
545
569
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
546
570
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
548
 
            safer_gnutls_strerror(ret));
 
571
    fprintf_plus(stderr,
 
572
                 "Error in GnuTLS session initialization: %s\n",
 
573
                 safer_gnutls_strerror(ret));
549
574
  }
550
575
  
551
576
  {
558
583
      }
559
584
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
560
585
    if(ret != GNUTLS_E_SUCCESS){
561
 
      fprintf(stderr, "Syntax error at: %s\n", err);
562
 
      fprintf(stderr, "GnuTLS error: %s\n",
563
 
              safer_gnutls_strerror(ret));
 
586
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
587
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
588
                   safer_gnutls_strerror(ret));
564
589
      gnutls_deinit(*session);
565
590
      return -1;
566
591
    }
575
600
    }
576
601
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
577
602
  if(ret != GNUTLS_E_SUCCESS){
578
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
579
 
            safer_gnutls_strerror(ret));
 
603
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
604
                 safer_gnutls_strerror(ret));
580
605
    gnutls_deinit(*session);
581
606
    return -1;
582
607
  }
627
652
    pf = PF_INET;
628
653
    break;
629
654
  default:
630
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
655
    fprintf_plus(stderr, "Bad address family: %d\n", af);
631
656
    errno = EINVAL;
632
657
    return -1;
633
658
  }
638
663
  }
639
664
  
640
665
  if(debug){
641
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
642
 
            "\n", ip, port);
 
666
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
667
                 PRIu16 "\n", ip, port);
643
668
  }
644
669
  
645
670
  tcp_sd = socket(pf, SOCK_STREAM, 0);
671
696
  }
672
697
  if(ret == 0){
673
698
    int e = errno;
674
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
699
    fprintf_plus(stderr, "Bad address: %s\n", ip);
675
700
    errno = e;
676
701
    goto mandos_end;
677
702
  }
682
707
    
683
708
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
684
709
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
685
 
                              -Wunreachable-code*/
 
710
                                -Wunreachable-code*/
686
711
      if(if_index == AVAHI_IF_UNSPEC){
687
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
688
 
                " without a network interface\n");
 
712
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
713
                     " incomplete without a network interface\n");
689
714
        errno = EINVAL;
690
715
        goto mandos_end;
691
716
      }
709
734
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
710
735
        perror_plus("if_indextoname");
711
736
      } else {
712
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
713
 
                ip, interface, port);
 
737
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
738
                     "\n", ip, interface, port);
714
739
      }
715
740
    } else {
716
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
717
 
              port);
 
741
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
742
                   ip, port);
718
743
    }
719
744
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
720
745
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
730
755
      perror_plus("inet_ntop");
731
756
    } else {
732
757
      if(strcmp(addrstr, ip) != 0){
733
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
758
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
734
759
      }
735
760
    }
736
761
  }
764
789
  while(true){
765
790
    size_t out_size = strlen(out);
766
791
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
767
 
                                   out_size - written));
 
792
                                        out_size - written));
768
793
    if(ret == -1){
769
794
      int e = errno;
770
795
      perror_plus("write");
790
815
  }
791
816
  
792
817
  if(debug){
793
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
818
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
794
819
  }
795
820
  
796
821
  if(quit_now){
798
823
    goto mandos_end;
799
824
  }
800
825
  
801
 
  /* Spurious warning from -Wint-to-pointer-cast */
802
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
826
  /* This casting via intptr_t is to eliminate warning about casting
 
827
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
828
     function "set-session-transport-fd!" does it. */
 
829
  gnutls_transport_set_ptr(session,
 
830
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
803
831
  
804
832
  if(quit_now){
805
833
    errno = EINTR;
816
844
  
817
845
  if(ret != GNUTLS_E_SUCCESS){
818
846
    if(debug){
819
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
847
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
820
848
      gnutls_perror(ret);
821
849
    }
822
850
    errno = EPROTO;
826
854
  /* Read OpenPGP packet that contains the wanted password */
827
855
  
828
856
  if(debug){
829
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
830
 
            ip);
 
857
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
858
                 " %s\n", ip);
831
859
  }
832
860
  
833
861
  while(true){
838
866
    }
839
867
    
840
868
    buffer_capacity = incbuffer(&buffer, buffer_length,
841
 
                                   buffer_capacity);
 
869
                                buffer_capacity);
842
870
    if(buffer_capacity == 0){
843
871
      int e = errno;
844
872
      perror_plus("incbuffer");
871
899
          }
872
900
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
873
901
        if(ret < 0){
874
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
902
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
903
                       "***\n");
875
904
          gnutls_perror(ret);
876
905
          errno = EPROTO;
877
906
          goto mandos_end;
878
907
        }
879
908
        break;
880
909
      default:
881
 
        fprintf(stderr, "Unknown error while reading data from"
882
 
                " encrypted session with Mandos server\n");
 
910
        fprintf_plus(stderr, "Unknown error while reading data from"
 
911
                     " encrypted session with Mandos server\n");
883
912
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
884
913
        errno = EIO;
885
914
        goto mandos_end;
890
919
  }
891
920
  
892
921
  if(debug){
893
 
    fprintf(stderr, "Closing TLS session\n");
 
922
    fprintf_plus(stderr, "Closing TLS session\n");
894
923
  }
895
924
  
896
925
  if(quit_now){
908
937
  
909
938
  if(buffer_length > 0){
910
939
    ssize_t decrypted_buffer_size;
911
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
912
 
                                               buffer_length,
 
940
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
913
941
                                               &decrypted_buffer);
914
942
    if(decrypted_buffer_size >= 0){
915
943
      
926
954
        if(ret == 0 and ferror(stdout)){
927
955
          int e = errno;
928
956
          if(debug){
929
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
930
 
                    strerror(errno));
 
957
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
958
                         strerror(errno));
931
959
          }
932
960
          errno = e;
933
961
          goto mandos_end;
990
1018
  switch(event){
991
1019
  default:
992
1020
  case AVAHI_RESOLVER_FAILURE:
993
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
994
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
995
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1021
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1022
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1023
                 domain,
 
1024
                 avahi_strerror(avahi_server_errno(mc.server)));
996
1025
    break;
997
1026
    
998
1027
  case AVAHI_RESOLVER_FOUND:
1000
1029
      char ip[AVAHI_ADDRESS_STR_MAX];
1001
1030
      avahi_address_snprint(ip, sizeof(ip), address);
1002
1031
      if(debug){
1003
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1004
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1005
 
                ip, (intmax_t)interface, port);
 
1032
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1033
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1034
                     host_name, ip, (intmax_t)interface, port);
1006
1035
      }
1007
1036
      int ret = start_mandos_communication(ip, port, interface,
1008
1037
                                           avahi_proto_to_af(proto));
1009
1038
      if(ret == 0){
1010
1039
        avahi_simple_poll_quit(mc.simple_poll);
1011
1040
      } else {
1012
 
        ret = add_server(ip, port, interface,
1013
 
                         avahi_proto_to_af(proto));
 
1041
        if(not add_server(ip, port, interface,
 
1042
                          avahi_proto_to_af(proto))){
 
1043
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1044
                       " list\n", name);
 
1045
        }
1014
1046
      }
1015
1047
    }
1016
1048
  }
1040
1072
  default:
1041
1073
  case AVAHI_BROWSER_FAILURE:
1042
1074
    
1043
 
    fprintf(stderr, "(Avahi browser) %s\n",
1044
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1075
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1076
                 avahi_strerror(avahi_server_errno(mc.server)));
1045
1077
    avahi_simple_poll_quit(mc.simple_poll);
1046
1078
    return;
1047
1079
    
1054
1086
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1055
1087
                                    name, type, domain, protocol, 0,
1056
1088
                                    resolve_callback, NULL) == NULL)
1057
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1058
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1089
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1090
                   " %s\n", name,
 
1091
                   avahi_strerror(avahi_server_errno(mc.server)));
1059
1092
    break;
1060
1093
    
1061
1094
  case AVAHI_BROWSER_REMOVE:
1064
1097
  case AVAHI_BROWSER_ALL_FOR_NOW:
1065
1098
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1066
1099
    if(debug){
1067
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1100
      fprintf_plus(stderr, "No Mandos server found, still"
 
1101
                   " searching...\n");
1068
1102
    }
1069
1103
    break;
1070
1104
  }
1085
1119
  errno = old_errno;
1086
1120
}
1087
1121
 
1088
 
/* 
1089
 
 * This function determines if a directory entry in /sys/class/net
1090
 
 * corresponds to an acceptable network device.
1091
 
 * (This function is passed to scandir(3) as a filter function.)
1092
 
 */
1093
 
int good_interface(const struct dirent *if_entry){
1094
 
  ssize_t ssret;
 
1122
bool get_flags(const char *ifname, struct ifreq *ifr){
1095
1123
  int ret;
1096
 
  if(if_entry->d_name[0] == '.'){
1097
 
    return 0;
1098
 
  }
 
1124
  
1099
1125
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1100
1126
  if(s < 0){
1101
1127
    perror_plus("socket");
1102
 
    return 0;
 
1128
    return false;
1103
1129
  }
1104
 
  struct ifreq ifr;
1105
 
  strcpy(ifr.ifr_name, if_entry->d_name);
1106
 
  ret = ioctl(s, SIOCGIFFLAGS, &ifr);
 
1130
  strcpy(ifr->ifr_name, ifname);
 
1131
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1107
1132
  if(ret == -1){
1108
1133
    if(debug){
1109
1134
      perror_plus("ioctl SIOCGIFFLAGS");
1110
1135
    }
1111
 
    return 0;
 
1136
    return false;
1112
1137
  }
 
1138
  return true;
 
1139
}
 
1140
 
 
1141
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1142
  
1113
1143
  /* Reject the loopback device */
1114
 
  if(ifr.ifr_flags & IFF_LOOPBACK){
 
1144
  if(ifr->ifr_flags & IFF_LOOPBACK){
1115
1145
    if(debug){
1116
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1117
 
              if_entry->d_name);
 
1146
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1147
                   ifname);
1118
1148
    }
1119
 
    return 0;
 
1149
    return false;
1120
1150
  }
1121
1151
  /* Accept point-to-point devices only if connect_to is specified */
1122
 
  if(connect_to != NULL and (ifr.ifr_flags & IFF_POINTOPOINT)){
 
1152
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1123
1153
    if(debug){
1124
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1125
 
              if_entry->d_name);
 
1154
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1155
                   " \"%s\"\n", ifname);
1126
1156
    }
1127
 
    return 1;
 
1157
    return true;
1128
1158
  }
1129
1159
  /* Otherwise, reject non-broadcast-capable devices */
1130
 
  if(not (ifr.ifr_flags & IFF_BROADCAST)){
 
1160
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1131
1161
    if(debug){
1132
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1133
 
              if_entry->d_name);
 
1162
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1163
                   " \"%s\"\n", ifname);
1134
1164
    }
1135
 
    return 0;
 
1165
    return false;
1136
1166
  }
1137
1167
  /* Reject non-ARP interfaces (including dummy interfaces) */
1138
 
  if(ifr.ifr_flags & IFF_NOARP){
 
1168
  if(ifr->ifr_flags & IFF_NOARP){
1139
1169
    if(debug){
1140
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1141
 
              if_entry->d_name);
 
1170
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1171
                   ifname);
1142
1172
    }
1143
 
    return 0;
 
1173
    return false;
1144
1174
  }
 
1175
  
1145
1176
  /* Accept this device */
1146
1177
  if(debug){
1147
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1148
 
            if_entry->d_name);
 
1178
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1179
  }
 
1180
  return true;
 
1181
}
 
1182
 
 
1183
/* 
 
1184
 * This function determines if a directory entry in /sys/class/net
 
1185
 * corresponds to an acceptable network device.
 
1186
 * (This function is passed to scandir(3) as a filter function.)
 
1187
 */
 
1188
int good_interface(const struct dirent *if_entry){
 
1189
  if(if_entry->d_name[0] == '.'){
 
1190
    return 0;
 
1191
  }
 
1192
  
 
1193
  struct ifreq ifr;
 
1194
  if(not get_flags(if_entry->d_name, &ifr)){
 
1195
    if(debug){
 
1196
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1197
                   "\"%s\"\n", if_entry->d_name);
 
1198
    }
 
1199
    return 0;
 
1200
  }
 
1201
  
 
1202
  if(not good_flags(if_entry->d_name, &ifr)){
 
1203
    return 0;
 
1204
  }
 
1205
  return 1;
 
1206
}
 
1207
 
 
1208
/* 
 
1209
 * This function determines if a directory entry in /sys/class/net
 
1210
 * corresponds to an acceptable network device which is up.
 
1211
 * (This function is passed to scandir(3) as a filter function.)
 
1212
 */
 
1213
int up_interface(const struct dirent *if_entry){
 
1214
  if(if_entry->d_name[0] == '.'){
 
1215
    return 0;
 
1216
  }
 
1217
  
 
1218
  struct ifreq ifr;
 
1219
  if(not get_flags(if_entry->d_name, &ifr)){
 
1220
    if(debug){
 
1221
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1222
                   "\"%s\"\n", if_entry->d_name);
 
1223
    }
 
1224
    return 0;
 
1225
  }
 
1226
  
 
1227
  /* Reject down interfaces */
 
1228
  if(not (ifr.ifr_flags & IFF_UP)){
 
1229
    if(debug){
 
1230
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1231
                   if_entry->d_name);
 
1232
    }
 
1233
    return 0;
 
1234
  }
 
1235
  
 
1236
  /* Reject non-running interfaces */
 
1237
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1238
    if(debug){
 
1239
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1240
                   if_entry->d_name);
 
1241
    }
 
1242
    return 0;
 
1243
  }
 
1244
  
 
1245
  if(not good_flags(if_entry->d_name, &ifr)){
 
1246
    return 0;
1149
1247
  }
1150
1248
  return 1;
1151
1249
}
1161
1259
  return 1;
1162
1260
}
1163
1261
 
 
1262
/* Is this directory entry a runnable program? */
 
1263
int runnable_hook(const struct dirent *direntry){
 
1264
  int ret;
 
1265
  size_t sret;
 
1266
  struct stat st;
 
1267
  
 
1268
  if((direntry->d_name)[0] == '\0'){
 
1269
    /* Empty name? */
 
1270
    return 0;
 
1271
  }
 
1272
  
 
1273
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1274
                "abcdefghijklmnopqrstuvwxyz"
 
1275
                "0123456789"
 
1276
                "_-");
 
1277
  if((direntry->d_name)[sret] != '\0'){
 
1278
    /* Contains non-allowed characters */
 
1279
    if(debug){
 
1280
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1281
                   direntry->d_name);
 
1282
    }
 
1283
    return 0;
 
1284
  }
 
1285
  
 
1286
  char *fullname = NULL;
 
1287
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1288
  if(ret < 0){
 
1289
    perror_plus("asprintf");
 
1290
    return 0;
 
1291
  }
 
1292
  
 
1293
  ret = stat(fullname, &st);
 
1294
  if(ret == -1){
 
1295
    if(debug){
 
1296
      perror_plus("Could not stat hook");
 
1297
    }
 
1298
    return 0;
 
1299
  }
 
1300
  if(not (S_ISREG(st.st_mode))){
 
1301
    /* Not a regular file */
 
1302
    if(debug){
 
1303
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1304
                   direntry->d_name);
 
1305
    }
 
1306
    return 0;
 
1307
  }
 
1308
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1309
    /* Not executable */
 
1310
    if(debug){
 
1311
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1312
                   direntry->d_name);
 
1313
    }
 
1314
    return 0;
 
1315
  }
 
1316
  if(debug){
 
1317
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1318
                 direntry->d_name);
 
1319
  }
 
1320
  return 1;
 
1321
}
 
1322
 
1164
1323
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1165
1324
  int ret;
1166
1325
  struct timespec now;
1170
1329
  while(true){
1171
1330
    if(mc.current_server == NULL){
1172
1331
      if (debug){
1173
 
        fprintf(stderr,
1174
 
                "Wait until first server is found. No timeout!\n");
 
1332
        fprintf_plus(stderr, "Wait until first server is found."
 
1333
                     " No timeout!\n");
1175
1334
      }
1176
1335
      ret = avahi_simple_poll_iterate(s, -1);
1177
1336
    } else {
1178
1337
      if (debug){
1179
 
        fprintf(stderr, "Check current_server if we should run it,"
1180
 
                " or wait\n");
 
1338
        fprintf_plus(stderr, "Check current_server if we should run"
 
1339
                     " it, or wait\n");
1181
1340
      }
1182
1341
      /* the current time */
1183
1342
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1199
1358
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1200
1359
      
1201
1360
      if (debug){
1202
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1361
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1362
                     block_time);
1203
1363
      }
1204
1364
      
1205
1365
      if(block_time <= 0){
1225
1385
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1226
1386
    }
1227
1387
    if(ret != 0){
1228
 
      if (ret > 0 or errno != EINTR) {
 
1388
      if (ret > 0 or errno != EINTR){
1229
1389
        return (ret != 1) ? ret : 0;
1230
1390
      }
1231
1391
    }
1232
1392
  }
1233
1393
}
1234
1394
 
 
1395
/* Set effective uid to 0, return errno */
 
1396
error_t raise_privileges(void){
 
1397
  error_t old_errno = errno;
 
1398
  error_t ret_errno = 0;
 
1399
  if(seteuid(0) == -1){
 
1400
    ret_errno = errno;
 
1401
    perror_plus("seteuid");
 
1402
  }
 
1403
  errno = old_errno;
 
1404
  return ret_errno;
 
1405
}
 
1406
 
 
1407
/* Set effective and real user ID to 0.  Return errno. */
 
1408
error_t raise_privileges_permanently(void){
 
1409
  error_t old_errno = errno;
 
1410
  error_t ret_errno = raise_privileges();
 
1411
  if(ret_errno != 0){
 
1412
    errno = old_errno;
 
1413
    return ret_errno;
 
1414
  }
 
1415
  if(setuid(0) == -1){
 
1416
    ret_errno = errno;
 
1417
    perror_plus("seteuid");
 
1418
  }
 
1419
  errno = old_errno;
 
1420
  return ret_errno;
 
1421
}
 
1422
 
 
1423
/* Set effective user ID to unprivileged saved user ID */
 
1424
error_t lower_privileges(void){
 
1425
  error_t old_errno = errno;
 
1426
  error_t ret_errno = 0;
 
1427
  if(seteuid(uid) == -1){
 
1428
    ret_errno = errno;
 
1429
    perror_plus("seteuid");
 
1430
  }
 
1431
  errno = old_errno;
 
1432
  return ret_errno;
 
1433
}
 
1434
 
 
1435
bool run_network_hooks(const char *mode, const char *interface,
 
1436
                       const float delay){
 
1437
  struct dirent **direntries;
 
1438
  struct dirent *direntry;
 
1439
  int ret;
 
1440
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1441
                         alphasort);
 
1442
  if(numhooks == -1){
 
1443
    perror_plus("scandir");
 
1444
  } else {
 
1445
    int devnull = open("/dev/null", O_RDONLY);
 
1446
    for(int i = 0; i < numhooks; i++){
 
1447
      direntry = direntries[i];
 
1448
      char *fullname = NULL;
 
1449
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1450
      if(ret < 0){
 
1451
        perror_plus("asprintf");
 
1452
        continue;
 
1453
      }
 
1454
      if(debug){
 
1455
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1456
                     direntry->d_name);
 
1457
      }
 
1458
      pid_t hook_pid = fork();
 
1459
      if(hook_pid == 0){
 
1460
        /* Child */
 
1461
        /* Raise privileges */
 
1462
        raise_privileges_permanently();
 
1463
        /* Set group */
 
1464
        errno = 0;
 
1465
        ret = setgid(0);
 
1466
        if(ret == -1){
 
1467
          perror_plus("setgid");
 
1468
        }
 
1469
        /* Reset supplementary groups */
 
1470
        errno = 0;
 
1471
        ret = setgroups(0, NULL);
 
1472
        if(ret == -1){
 
1473
          perror_plus("setgroups");
 
1474
        }
 
1475
        dup2(devnull, STDIN_FILENO);
 
1476
        close(devnull);
 
1477
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1478
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1479
        if(ret == -1){
 
1480
          perror_plus("setenv");
 
1481
          _exit(EX_OSERR);
 
1482
        }
 
1483
        ret = setenv("DEVICE", interface, 1);
 
1484
        if(ret == -1){
 
1485
          perror_plus("setenv");
 
1486
          _exit(EX_OSERR);
 
1487
        }
 
1488
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1489
        if(ret == -1){
 
1490
          perror_plus("setenv");
 
1491
          _exit(EX_OSERR);
 
1492
        }
 
1493
        ret = setenv("MODE", mode, 1);
 
1494
        if(ret == -1){
 
1495
          perror_plus("setenv");
 
1496
          _exit(EX_OSERR);
 
1497
        }
 
1498
        char *delaystring;
 
1499
        ret = asprintf(&delaystring, "%f", delay);
 
1500
        if(ret == -1){
 
1501
          perror_plus("asprintf");
 
1502
          _exit(EX_OSERR);
 
1503
        }
 
1504
        ret = setenv("DELAY", delaystring, 1);
 
1505
        if(ret == -1){
 
1506
          free(delaystring);
 
1507
          perror_plus("setenv");
 
1508
          _exit(EX_OSERR);
 
1509
        }
 
1510
        free(delaystring);
 
1511
        if(connect_to != NULL){
 
1512
          ret = setenv("CONNECT", connect_to, 1);
 
1513
          if(ret == -1){
 
1514
            perror_plus("setenv");
 
1515
            _exit(EX_OSERR);
 
1516
          }
 
1517
        }
 
1518
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1519
          perror_plus("execl");
 
1520
          _exit(EXIT_FAILURE);
 
1521
        }
 
1522
      } else {
 
1523
        int status;
 
1524
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1525
          perror_plus("waitpid");
 
1526
          free(fullname);
 
1527
          continue;
 
1528
        }
 
1529
        if(WIFEXITED(status)){
 
1530
          if(WEXITSTATUS(status) != 0){
 
1531
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1532
                         " with status %d\n", direntry->d_name,
 
1533
                         WEXITSTATUS(status));
 
1534
            free(fullname);
 
1535
            continue;
 
1536
          }
 
1537
        } else if(WIFSIGNALED(status)){
 
1538
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1539
                       " signal %d\n", direntry->d_name,
 
1540
                       WTERMSIG(status));
 
1541
          free(fullname);
 
1542
          continue;
 
1543
        } else {
 
1544
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1545
                       " crashed\n", direntry->d_name);
 
1546
          free(fullname);
 
1547
          continue;
 
1548
        }
 
1549
      }
 
1550
      free(fullname);
 
1551
      if(debug){
 
1552
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1553
                     direntry->d_name);
 
1554
      }
 
1555
    }
 
1556
    close(devnull);
 
1557
  }
 
1558
  return true;
 
1559
}
 
1560
 
 
1561
int bring_up_interface(const char *const interface,
 
1562
                       const float delay){
 
1563
  int sd = -1;
 
1564
  int old_errno = errno;
 
1565
  int ret_errno = 0;
 
1566
  int ret;
 
1567
  struct ifreq network;
 
1568
  AvahiIfIndex if_index = (AvahiIfIndex)if_nametoindex(interface);
 
1569
  if(if_index == 0){
 
1570
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1571
    errno = old_errno;
 
1572
    return ENXIO;
 
1573
  }
 
1574
  
 
1575
  if(quit_now){
 
1576
    errno = old_errno;
 
1577
    return EINTR;
 
1578
  }
 
1579
  
 
1580
  /* Re-raise priviliges */
 
1581
  raise_privileges();
 
1582
  
 
1583
#ifdef __linux__
 
1584
  /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1585
     messages about the network interface to mess up the prompt */
 
1586
  ret = klogctl(8, NULL, 5);
 
1587
  bool restore_loglevel = true;
 
1588
  if(ret == -1){
 
1589
    restore_loglevel = false;
 
1590
    perror_plus("klogctl");
 
1591
  }
 
1592
#endif  /* __linux__ */
 
1593
    
 
1594
  sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1595
  if(sd < 0){
 
1596
    ret_errno = errno;
 
1597
    perror_plus("socket");
 
1598
#ifdef __linux__
 
1599
    if(restore_loglevel){
 
1600
      ret = klogctl(7, NULL, 0);
 
1601
      if(ret == -1){
 
1602
        perror_plus("klogctl");
 
1603
      }
 
1604
    }
 
1605
#endif  /* __linux__ */
 
1606
    /* Lower privileges */
 
1607
    lower_privileges();
 
1608
    errno = old_errno;
 
1609
    return ret_errno;
 
1610
  }
 
1611
  strcpy(network.ifr_name, interface);
 
1612
  ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1613
  if(ret == -1){
 
1614
    ret_errno = errno;
 
1615
    perror_plus("ioctl SIOCGIFFLAGS");
 
1616
#ifdef __linux__
 
1617
    if(restore_loglevel){
 
1618
      ret = klogctl(7, NULL, 0);
 
1619
      if(ret == -1){
 
1620
        perror_plus("klogctl");
 
1621
      }
 
1622
    }
 
1623
#endif  /* __linux__ */
 
1624
    /* Lower privileges */
 
1625
    lower_privileges();
 
1626
    errno = old_errno;
 
1627
    return ret_errno;
 
1628
  }
 
1629
  if((network.ifr_flags & IFF_UP) == 0){
 
1630
    network.ifr_flags |= IFF_UP;
 
1631
    ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1632
    if(ret == -1){
 
1633
      ret_errno = errno;
 
1634
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1635
#ifdef __linux__
 
1636
      if(restore_loglevel){
 
1637
        ret = klogctl(7, NULL, 0);
 
1638
        if(ret == -1){
 
1639
          perror_plus("klogctl");
 
1640
        }
 
1641
      }
 
1642
#endif  /* __linux__ */
 
1643
        /* Lower privileges */
 
1644
      lower_privileges();
 
1645
      errno = old_errno;
 
1646
      return ret_errno;
 
1647
    }
 
1648
  }
 
1649
  /* Sleep checking until interface is running.
 
1650
     Check every 0.25s, up to total time of delay */
 
1651
  for(int i=0; i < delay * 4; i++){
 
1652
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1653
    if(ret == -1){
 
1654
      perror_plus("ioctl SIOCGIFFLAGS");
 
1655
    } else if(network.ifr_flags & IFF_RUNNING){
 
1656
      break;
 
1657
    }
 
1658
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1659
    ret = nanosleep(&sleeptime, NULL);
 
1660
    if(ret == -1 and errno != EINTR){
 
1661
      perror_plus("nanosleep");
 
1662
    }
 
1663
  }
 
1664
  /* Close the socket */
 
1665
  ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1666
  if(ret == -1){
 
1667
    perror_plus("close");
 
1668
  }
 
1669
#ifdef __linux__
 
1670
  if(restore_loglevel){
 
1671
    /* Restores kernel loglevel to default */
 
1672
    ret = klogctl(7, NULL, 0);
 
1673
    if(ret == -1){
 
1674
      perror_plus("klogctl");
 
1675
    }
 
1676
  }
 
1677
#endif  /* __linux__ */
 
1678
  /* Lower privileges */
 
1679
  lower_privileges();
 
1680
  errno = old_errno;
 
1681
  return 0;
 
1682
}
 
1683
 
1235
1684
int main(int argc, char *argv[]){
1236
1685
  AvahiSServiceBrowser *sb = NULL;
1237
1686
  int error;
1243
1692
  struct ifreq network;
1244
1693
  int sd = -1;
1245
1694
  bool take_down_interface = false;
1246
 
  uid_t uid;
1247
 
  gid_t gid;
1248
1695
  char tempdir[] = "/tmp/mandosXXXXXX";
1249
1696
  bool tempdir_created = false;
1250
1697
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1317
1764
        .group = 2 },
1318
1765
      { .name = "retry", .key = 132,
1319
1766
        .arg = "SECONDS",
1320
 
        .doc = "Retry interval used when denied by the mandos server",
 
1767
        .doc = "Retry interval used when denied by the Mandos server",
 
1768
        .group = 2 },
 
1769
      { .name = "network-hook-dir", .key = 133,
 
1770
        .arg = "DIR",
 
1771
        .doc = "Directory where network hooks are located",
1321
1772
        .group = 2 },
1322
1773
      /*
1323
1774
       * These reproduce what we would get without ARGP_NO_HELP
1377
1828
          argp_error(state, "Bad retry interval");
1378
1829
        }
1379
1830
        break;
 
1831
      case 133:                 /* --network-hook-dir */
 
1832
        hookdir = arg;
 
1833
        break;
1380
1834
        /*
1381
1835
         * These reproduce what we would get without ARGP_NO_HELP
1382
1836
         */
1388
1842
        argp_state_help(state, state->out_stream,
1389
1843
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1390
1844
      case 'V':                 /* --version */
1391
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1845
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1392
1846
        exit(argp_err_exit_status);
1393
1847
        break;
1394
1848
      default:
1421
1875
  {
1422
1876
    /* Work around Debian bug #633582:
1423
1877
       <http://bugs.debian.org/633582> */
1424
 
    struct stat st;
1425
1878
    
1426
1879
    /* Re-raise priviliges */
1427
 
    errno = 0;
1428
 
    ret = seteuid(0);
1429
 
    if(ret == -1){
1430
 
      perror_plus("seteuid");
1431
 
    }
1432
 
    
1433
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1434
 
      int seckey_fd = open(seckey, O_RDONLY);
1435
 
      if(seckey_fd == -1){
1436
 
        perror_plus("open");
1437
 
      } else {
1438
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1439
 
        if(ret == -1){
1440
 
          perror_plus("fstat");
1441
 
        } else {
1442
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1443
 
            ret = fchown(seckey_fd, uid, gid);
1444
 
            if(ret == -1){
1445
 
              perror_plus("fchown");
1446
 
            }
1447
 
          }
1448
 
        }
1449
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1450
 
      }
1451
 
    }
1452
 
    
1453
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1454
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1455
 
      if(pubkey_fd == -1){
1456
 
        perror_plus("open");
1457
 
      } else {
1458
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1459
 
        if(ret == -1){
1460
 
          perror_plus("fstat");
1461
 
        } else {
1462
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1463
 
            ret = fchown(pubkey_fd, uid, gid);
1464
 
            if(ret == -1){
1465
 
              perror_plus("fchown");
1466
 
            }
1467
 
          }
1468
 
        }
1469
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1470
 
      }
1471
 
    }
1472
 
    
1473
 
    /* Lower privileges */
1474
 
    errno = 0;
1475
 
    ret = seteuid(uid);
1476
 
    if(ret == -1){
1477
 
      perror_plus("seteuid");
1478
 
    }
 
1880
    if(raise_privileges() == 0){
 
1881
      struct stat st;
 
1882
      
 
1883
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1884
        int seckey_fd = open(seckey, O_RDONLY);
 
1885
        if(seckey_fd == -1){
 
1886
          perror_plus("open");
 
1887
        } else {
 
1888
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1889
          if(ret == -1){
 
1890
            perror_plus("fstat");
 
1891
          } else {
 
1892
            if(S_ISREG(st.st_mode)
 
1893
               and st.st_uid == 0 and st.st_gid == 0){
 
1894
              ret = fchown(seckey_fd, uid, gid);
 
1895
              if(ret == -1){
 
1896
                perror_plus("fchown");
 
1897
              }
 
1898
            }
 
1899
          }
 
1900
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1901
        }
 
1902
      }
 
1903
    
 
1904
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1905
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1906
        if(pubkey_fd == -1){
 
1907
          perror_plus("open");
 
1908
        } else {
 
1909
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1910
          if(ret == -1){
 
1911
            perror_plus("fstat");
 
1912
          } else {
 
1913
            if(S_ISREG(st.st_mode)
 
1914
               and st.st_uid == 0 and st.st_gid == 0){
 
1915
              ret = fchown(pubkey_fd, uid, gid);
 
1916
              if(ret == -1){
 
1917
                perror_plus("fchown");
 
1918
              }
 
1919
            }
 
1920
          }
 
1921
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1922
        }
 
1923
      }
 
1924
    
 
1925
      /* Lower privileges */
 
1926
      errno = 0;
 
1927
      ret = seteuid(uid);
 
1928
      if(ret == -1){
 
1929
        perror_plus("seteuid");
 
1930
      }
 
1931
    }
 
1932
  }
 
1933
  
 
1934
  /* Run network hooks */
 
1935
  if(not run_network_hooks("start", interface, delay)){
 
1936
    goto end;
1479
1937
  }
1480
1938
  
1481
1939
  if(not debug){
1482
1940
    avahi_set_log_function(empty_log);
1483
1941
  }
1484
 
 
 
1942
  
1485
1943
  if(interface[0] == '\0'){
1486
1944
    struct dirent **direntries;
1487
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1945
    /* First look for interfaces that are up */
 
1946
    ret = scandir(sys_class_net, &direntries, up_interface,
1488
1947
                  alphasort);
 
1948
    if(ret == 0){
 
1949
      /* No up interfaces, look for any good interfaces */
 
1950
      free(direntries);
 
1951
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1952
                    alphasort);
 
1953
    }
1489
1954
    if(ret >= 1){
1490
 
      /* Pick the first good interface */
 
1955
      /* Pick the first interface returned */
1491
1956
      interface = strdup(direntries[0]->d_name);
1492
1957
      if(debug){
1493
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1958
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1494
1959
      }
1495
1960
      if(interface == NULL){
1496
1961
        perror_plus("malloc");
1501
1966
      free(direntries);
1502
1967
    } else {
1503
1968
      free(direntries);
1504
 
      fprintf(stderr, "Could not find a network interface\n");
 
1969
      fprintf_plus(stderr, "Could not find a network interface\n");
1505
1970
      exitcode = EXIT_FAILURE;
1506
1971
      goto end;
1507
1972
    }
1513
1978
  srand((unsigned int) time(NULL));
1514
1979
  mc.simple_poll = avahi_simple_poll_new();
1515
1980
  if(mc.simple_poll == NULL){
1516
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1981
    fprintf_plus(stderr,
 
1982
                 "Avahi: Failed to create simple poll object.\n");
1517
1983
    exitcode = EX_UNAVAILABLE;
1518
1984
    goto end;
1519
1985
  }
1582
2048
  }
1583
2049
  
1584
2050
  /* If the interface is down, bring it up */
1585
 
  if(strcmp(interface, "none") != 0){
1586
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1587
 
    if(if_index == 0){
1588
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1589
 
      exitcode = EX_UNAVAILABLE;
1590
 
      goto end;
1591
 
    }
1592
 
    
1593
 
    if(quit_now){
1594
 
      goto end;
1595
 
    }
1596
 
    
1597
 
    /* Re-raise priviliges */
1598
 
    errno = 0;
1599
 
    ret = seteuid(0);
1600
 
    if(ret == -1){
1601
 
      perror_plus("seteuid");
1602
 
    }
1603
 
    
1604
 
#ifdef __linux__
1605
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1606
 
       messages about the network interface to mess up the prompt */
1607
 
    ret = klogctl(8, NULL, 5);
1608
 
    bool restore_loglevel = true;
1609
 
    if(ret == -1){
1610
 
      restore_loglevel = false;
1611
 
      perror_plus("klogctl");
1612
 
    }
1613
 
#endif  /* __linux__ */
1614
 
    
1615
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1616
 
    if(sd < 0){
1617
 
      perror_plus("socket");
1618
 
      exitcode = EX_OSERR;
1619
 
#ifdef __linux__
1620
 
      if(restore_loglevel){
1621
 
        ret = klogctl(7, NULL, 0);
1622
 
        if(ret == -1){
1623
 
          perror_plus("klogctl");
1624
 
        }
1625
 
      }
1626
 
#endif  /* __linux__ */
1627
 
      /* Lower privileges */
1628
 
      errno = 0;
1629
 
      ret = seteuid(uid);
1630
 
      if(ret == -1){
1631
 
        perror_plus("seteuid");
1632
 
      }
1633
 
      goto end;
1634
 
    }
1635
 
    strcpy(network.ifr_name, interface);
1636
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1637
 
    if(ret == -1){
1638
 
      perror_plus("ioctl SIOCGIFFLAGS");
1639
 
#ifdef __linux__
1640
 
      if(restore_loglevel){
1641
 
        ret = klogctl(7, NULL, 0);
1642
 
        if(ret == -1){
1643
 
          perror_plus("klogctl");
1644
 
        }
1645
 
      }
1646
 
#endif  /* __linux__ */
1647
 
      exitcode = EX_OSERR;
1648
 
      /* Lower privileges */
1649
 
      errno = 0;
1650
 
      ret = seteuid(uid);
1651
 
      if(ret == -1){
1652
 
        perror_plus("seteuid");
1653
 
      }
1654
 
      goto end;
1655
 
    }
1656
 
    if((network.ifr_flags & IFF_UP) == 0){
1657
 
      network.ifr_flags |= IFF_UP;
1658
 
      take_down_interface = true;
1659
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1660
 
      if(ret == -1){
1661
 
        take_down_interface = false;
1662
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1663
 
        exitcode = EX_OSERR;
1664
 
#ifdef __linux__
1665
 
        if(restore_loglevel){
1666
 
          ret = klogctl(7, NULL, 0);
1667
 
          if(ret == -1){
1668
 
            perror_plus("klogctl");
1669
 
          }
1670
 
        }
1671
 
#endif  /* __linux__ */
1672
 
        /* Lower privileges */
1673
 
        errno = 0;
1674
 
        ret = seteuid(uid);
1675
 
        if(ret == -1){
1676
 
          perror_plus("seteuid");
1677
 
        }
1678
 
        goto end;
1679
 
      }
1680
 
    }
1681
 
    /* Sleep checking until interface is running.
1682
 
       Check every 0.25s, up to total time of delay */
1683
 
    for(int i=0; i < delay * 4; i++){
1684
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1685
 
      if(ret == -1){
1686
 
        perror_plus("ioctl SIOCGIFFLAGS");
1687
 
      } else if(network.ifr_flags & IFF_RUNNING){
1688
 
        break;
1689
 
      }
1690
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1691
 
      ret = nanosleep(&sleeptime, NULL);
1692
 
      if(ret == -1 and errno != EINTR){
1693
 
        perror_plus("nanosleep");
1694
 
      }
1695
 
    }
1696
 
    if(not take_down_interface){
1697
 
      /* We won't need the socket anymore */
1698
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1699
 
      if(ret == -1){
1700
 
        perror_plus("close");
1701
 
      }
1702
 
    }
1703
 
#ifdef __linux__
1704
 
    if(restore_loglevel){
1705
 
      /* Restores kernel loglevel to default */
1706
 
      ret = klogctl(7, NULL, 0);
1707
 
      if(ret == -1){
1708
 
        perror_plus("klogctl");
1709
 
      }
1710
 
    }
1711
 
#endif  /* __linux__ */
1712
 
    /* Lower privileges */
1713
 
    errno = 0;
1714
 
    if(take_down_interface){
1715
 
      /* Lower privileges */
1716
 
      ret = seteuid(uid);
1717
 
      if(ret == -1){
1718
 
        perror_plus("seteuid");
1719
 
      }
1720
 
    } else {
1721
 
      /* Lower privileges permanently */
1722
 
      ret = setuid(uid);
1723
 
      if(ret == -1){
1724
 
        perror_plus("setuid");
1725
 
      }
 
2051
  if((interface[0] != '\0') and (strcmp(interface, "none") != 0)){
 
2052
    ret = bring_up_interface(interface, delay);
 
2053
    if(ret != 0){
 
2054
      errno = ret;
 
2055
      perror_plus("Failed to bring up interface");
1726
2056
    }
1727
2057
  }
1728
2058
  
1732
2062
  
1733
2063
  ret = init_gnutls_global(pubkey, seckey);
1734
2064
  if(ret == -1){
1735
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2065
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1736
2066
    exitcode = EX_UNAVAILABLE;
1737
2067
    goto end;
1738
2068
  } else {
1754
2084
  }
1755
2085
  
1756
2086
  if(not init_gpgme(pubkey, seckey, tempdir)){
1757
 
    fprintf(stderr, "init_gpgme failed\n");
 
2087
    fprintf_plus(stderr, "init_gpgme failed\n");
1758
2088
    exitcode = EX_UNAVAILABLE;
1759
2089
    goto end;
1760
2090
  } else {
1769
2099
    /* Connect directly, do not use Zeroconf */
1770
2100
    /* (Mainly meant for debugging) */
1771
2101
    char *address = strrchr(connect_to, ':');
 
2102
    
1772
2103
    if(address == NULL){
1773
 
      fprintf(stderr, "No colon in address\n");
 
2104
      fprintf_plus(stderr, "No colon in address\n");
1774
2105
      exitcode = EX_USAGE;
1775
2106
      goto end;
1776
2107
    }
1784
2115
    tmpmax = strtoimax(address+1, &tmp, 10);
1785
2116
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1786
2117
       or tmpmax != (uint16_t)tmpmax){
1787
 
      fprintf(stderr, "Bad port number\n");
 
2118
      fprintf_plus(stderr, "Bad port number\n");
1788
2119
      exitcode = EX_USAGE;
1789
2120
      goto end;
1790
2121
    }
1820
2151
        break;
1821
2152
      }
1822
2153
      if(debug){
1823
 
        fprintf(stderr, "Retrying in %d seconds\n",
1824
 
                (int)retry_interval);
 
2154
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2155
                     (int)retry_interval);
1825
2156
      }
1826
2157
      sleep((int)retry_interval);
1827
2158
    }
1829
2160
    if (not quit_now){
1830
2161
      exitcode = EXIT_SUCCESS;
1831
2162
    }
1832
 
 
 
2163
    
1833
2164
    goto end;
1834
2165
  }
1835
2166
  
1857
2188
  
1858
2189
  /* Check if creating the Avahi server object succeeded */
1859
2190
  if(mc.server == NULL){
1860
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1861
 
            avahi_strerror(error));
 
2191
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2192
                 avahi_strerror(error));
1862
2193
    exitcode = EX_UNAVAILABLE;
1863
2194
    goto end;
1864
2195
  }
1872
2203
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1873
2204
                                   NULL, 0, browse_callback, NULL);
1874
2205
  if(sb == NULL){
1875
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1876
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2206
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2207
                 avahi_strerror(avahi_server_errno(mc.server)));
1877
2208
    exitcode = EX_UNAVAILABLE;
1878
2209
    goto end;
1879
2210
  }
1885
2216
  /* Run the main loop */
1886
2217
  
1887
2218
  if(debug){
1888
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2219
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1889
2220
  }
1890
2221
 
1891
2222
  ret = avahi_loop_with_timeout(mc.simple_poll,
1892
2223
                                (int)(retry_interval * 1000));
1893
2224
  if(debug){
1894
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1895
 
            (ret == 0) ? "successfully" : "with error");
 
2225
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2226
                 (ret == 0) ? "successfully" : "with error");
1896
2227
  }
1897
2228
  
1898
2229
 end:
1899
2230
  
1900
2231
  if(debug){
1901
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2232
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1902
2233
  }
1903
2234
  
1904
2235
  /* Cleanup things */
1920
2251
  if(gpgme_initialized){
1921
2252
    gpgme_release(mc.ctx);
1922
2253
  }
1923
 
 
 
2254
  
1924
2255
  /* Cleans up the circular linked list of Mandos servers the client
1925
2256
     has seen */
1926
2257
  if(mc.current_server != NULL){
1932
2263
    }
1933
2264
  }
1934
2265
  
1935
 
  /* Take down the network interface */
1936
 
  if(take_down_interface){
1937
 
    /* Re-raise priviliges */
1938
 
    errno = 0;
1939
 
    ret = seteuid(0);
1940
 
    if(ret == -1){
1941
 
      perror_plus("seteuid");
1942
 
    }
1943
 
    if(geteuid() == 0){
 
2266
  /* Run network hooks */
 
2267
  run_network_hooks("stop", interface, delay);
 
2268
  
 
2269
  /* Re-raise priviliges */
 
2270
  {
 
2271
    raise_privileges();
 
2272
    
 
2273
    /* Take down the network interface */
 
2274
    if(take_down_interface and geteuid() == 0){
1944
2275
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1945
2276
      if(ret == -1){
1946
2277
        perror_plus("ioctl SIOCGIFFLAGS");
1947
 
      } else if(network.ifr_flags & IFF_UP) {
 
2278
      } else if(network.ifr_flags & IFF_UP){
1948
2279
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1949
2280
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1950
2281
        if(ret == -1){
1955
2286
      if(ret == -1){
1956
2287
        perror_plus("close");
1957
2288
      }
1958
 
      /* Lower privileges permanently */
1959
 
      errno = 0;
1960
 
      ret = setuid(uid);
1961
 
      if(ret == -1){
1962
 
        perror_plus("setuid");
1963
 
      }
1964
2289
    }
1965
2290
  }
 
2291
  /* Lower privileges permanently */
 
2292
  errno = 0;
 
2293
  ret = setuid(uid);
 
2294
  if(ret == -1){
 
2295
    perror_plus("setuid");
 
2296
  }
1966
2297
  
1967
2298
  /* Removes the GPGME temp directory and all files inside */
1968
2299
  if(tempdir_created){
1982
2313
        }
1983
2314
        ret = remove(fullname);
1984
2315
        if(ret == -1){
1985
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1986
 
                  strerror(errno));
 
2316
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2317
                       strerror(errno));
1987
2318
        }
1988
2319
        free(fullname);
1989
2320
      }