/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-07 21:00:57 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120607210057-9k4mou58uht7sj2m
* plugins.d/mandos-client.c (bring_up_interface): Bug fix: Return
                                                  errno code.  Don't
                                                  modify errno.

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;
1095
 
  char *flagname = NULL;
1096
 
  if(if_entry->d_name[0] == '.'){
1097
 
    return 0;
1098
 
  }
1099
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1100
 
                     if_entry->d_name);
1101
 
  if(ret < 0){
1102
 
    perror_plus("asprintf");
1103
 
    return 0;
1104
 
  }
1105
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1106
 
  if(flags_fd == -1){
1107
 
    perror_plus("open");
1108
 
    free(flagname);
1109
 
    return 0;
1110
 
  }
1111
 
  free(flagname);
1112
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1113
 
  /* read line from flags_fd */
1114
 
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
1115
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1116
 
  flagstring[(size_t)to_read] = '\0';
1117
 
  if(flagstring == NULL){
1118
 
    perror_plus("malloc");
1119
 
    close(flags_fd);
1120
 
    return 0;
1121
 
  }
1122
 
  while(to_read > 0){
1123
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1124
 
                                             (size_t)to_read));
1125
 
    if(ssret == -1){
1126
 
      perror_plus("read");
1127
 
      free(flagstring);
1128
 
      close(flags_fd);
1129
 
      return 0;
1130
 
    }
1131
 
    to_read -= ssret;
1132
 
    if(ssret == 0){
1133
 
      break;
1134
 
    }
1135
 
  }
1136
 
  close(flags_fd);
1137
 
  intmax_t tmpmax;
1138
 
  char *tmp;
1139
 
  errno = 0;
1140
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1141
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1142
 
                                         and not (isspace(*tmp)))
1143
 
     or tmpmax != (ifreq_flags)tmpmax){
 
1122
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1123
  int ret;
 
1124
  
 
1125
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1126
  if(s < 0){
 
1127
    perror_plus("socket");
 
1128
    return false;
 
1129
  }
 
1130
  strcpy(ifr->ifr_name, ifname);
 
1131
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1132
  if(ret == -1){
1144
1133
    if(debug){
1145
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1146
 
              flagstring, if_entry->d_name);
 
1134
      perror_plus("ioctl SIOCGIFFLAGS");
1147
1135
    }
1148
 
    free(flagstring);
1149
 
    return 0;
 
1136
    return false;
1150
1137
  }
1151
 
  free(flagstring);
1152
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1138
  return true;
 
1139
}
 
1140
 
 
1141
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1142
  
1153
1143
  /* Reject the loopback device */
1154
 
  if(flags & IFF_LOOPBACK){
 
1144
  if(ifr->ifr_flags & IFF_LOOPBACK){
1155
1145
    if(debug){
1156
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1157
 
              if_entry->d_name);
 
1146
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1147
                   ifname);
1158
1148
    }
1159
 
    return 0;
 
1149
    return false;
1160
1150
  }
1161
1151
  /* Accept point-to-point devices only if connect_to is specified */
1162
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1152
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1163
1153
    if(debug){
1164
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1165
 
              if_entry->d_name);
 
1154
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1155
                   " \"%s\"\n", ifname);
1166
1156
    }
1167
 
    return 1;
 
1157
    return true;
1168
1158
  }
1169
1159
  /* Otherwise, reject non-broadcast-capable devices */
1170
 
  if(not (flags & IFF_BROADCAST)){
 
1160
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1171
1161
    if(debug){
1172
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1173
 
              if_entry->d_name);
 
1162
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1163
                   " \"%s\"\n", ifname);
1174
1164
    }
1175
 
    return 0;
 
1165
    return false;
1176
1166
  }
1177
1167
  /* Reject non-ARP interfaces (including dummy interfaces) */
1178
 
  if(flags & IFF_NOARP){
 
1168
  if(ifr->ifr_flags & IFF_NOARP){
1179
1169
    if(debug){
1180
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1181
 
              if_entry->d_name);
 
1170
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1171
                   ifname);
1182
1172
    }
1183
 
    return 0;
 
1173
    return false;
1184
1174
  }
 
1175
  
1185
1176
  /* Accept this device */
1186
1177
  if(debug){
1187
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1188
 
            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;
1189
1247
  }
1190
1248
  return 1;
1191
1249
}
1201
1259
  return 1;
1202
1260
}
1203
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
 
1204
1323
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1205
1324
  int ret;
1206
1325
  struct timespec now;
1210
1329
  while(true){
1211
1330
    if(mc.current_server == NULL){
1212
1331
      if (debug){
1213
 
        fprintf(stderr,
1214
 
                "Wait until first server is found. No timeout!\n");
 
1332
        fprintf_plus(stderr, "Wait until first server is found."
 
1333
                     " No timeout!\n");
1215
1334
      }
1216
1335
      ret = avahi_simple_poll_iterate(s, -1);
1217
1336
    } else {
1218
1337
      if (debug){
1219
 
        fprintf(stderr, "Check current_server if we should run it,"
1220
 
                " or wait\n");
 
1338
        fprintf_plus(stderr, "Check current_server if we should run"
 
1339
                     " it, or wait\n");
1221
1340
      }
1222
1341
      /* the current time */
1223
1342
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1239
1358
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1240
1359
      
1241
1360
      if (debug){
1242
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1361
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1362
                     block_time);
1243
1363
      }
1244
1364
      
1245
1365
      if(block_time <= 0){
1265
1385
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1266
1386
    }
1267
1387
    if(ret != 0){
1268
 
      if (ret > 0 or errno != EINTR) {
 
1388
      if (ret > 0 or errno != EINTR){
1269
1389
        return (ret != 1) ? ret : 0;
1270
1390
      }
1271
1391
    }
1272
1392
  }
1273
1393
}
1274
1394
 
 
1395
/* Set effective uid to 0, return errno */
 
1396
int raise_privileges(void){
 
1397
  int old_errno = errno;
 
1398
  int ret_errno = 0;
 
1399
  errno = 0;
 
1400
  if(seteuid(0) == -1){
 
1401
    perror_plus("seteuid");
 
1402
  }
 
1403
  ret_errno = errno;
 
1404
  errno = old_errno;
 
1405
  return ret_errno;
 
1406
}
 
1407
 
 
1408
/* Set effective and real user ID to 0.  Return errno. */
 
1409
int raise_privileges_permanently(void){
 
1410
  int old_errno = errno;
 
1411
  int ret_errno = raise_privileges();
 
1412
  if(ret_errno != 0){
 
1413
    errno = old_errno;
 
1414
    return ret_errno;
 
1415
  }
 
1416
  errno = 0;
 
1417
  if(setuid(0) == -1){
 
1418
    perror_plus("seteuid");
 
1419
  }
 
1420
  ret_errno = errno;
 
1421
  errno = old_errno;
 
1422
  return ret_errno;
 
1423
}
 
1424
 
 
1425
/* Set effective user ID to unprivileged saved user ID */
 
1426
int lower_privileges(void){
 
1427
  int old_errno = errno;
 
1428
  int ret_errno = 0;
 
1429
  errno = 0;
 
1430
  if(seteuid(uid) == -1){
 
1431
    perror_plus("seteuid");
 
1432
  }
 
1433
  ret_errno = errno;
 
1434
  errno = old_errno;
 
1435
  return ret_errno;
 
1436
}
 
1437
 
 
1438
bool run_network_hooks(const char *mode, const char *interface,
 
1439
                       const float delay){
 
1440
  struct dirent **direntries;
 
1441
  struct dirent *direntry;
 
1442
  int ret;
 
1443
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1444
                         alphasort);
 
1445
  if(numhooks == -1){
 
1446
    perror_plus("scandir");
 
1447
  } else {
 
1448
    int devnull = open("/dev/null", O_RDONLY);
 
1449
    for(int i = 0; i < numhooks; i++){
 
1450
      direntry = direntries[i];
 
1451
      char *fullname = NULL;
 
1452
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1453
      if(ret < 0){
 
1454
        perror_plus("asprintf");
 
1455
        continue;
 
1456
      }
 
1457
      if(debug){
 
1458
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1459
                     direntry->d_name);
 
1460
      }
 
1461
      pid_t hook_pid = fork();
 
1462
      if(hook_pid == 0){
 
1463
        /* Child */
 
1464
        /* Raise privileges */
 
1465
        raise_privileges_permanently();
 
1466
        /* Set group */
 
1467
        errno = 0;
 
1468
        ret = setgid(0);
 
1469
        if(ret == -1){
 
1470
          perror_plus("setgid");
 
1471
        }
 
1472
        /* Reset supplementary groups */
 
1473
        errno = 0;
 
1474
        ret = setgroups(0, NULL);
 
1475
        if(ret == -1){
 
1476
          perror_plus("setgroups");
 
1477
        }
 
1478
        dup2(devnull, STDIN_FILENO);
 
1479
        close(devnull);
 
1480
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1481
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1482
        if(ret == -1){
 
1483
          perror_plus("setenv");
 
1484
          _exit(EX_OSERR);
 
1485
        }
 
1486
        ret = setenv("DEVICE", interface, 1);
 
1487
        if(ret == -1){
 
1488
          perror_plus("setenv");
 
1489
          _exit(EX_OSERR);
 
1490
        }
 
1491
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1492
        if(ret == -1){
 
1493
          perror_plus("setenv");
 
1494
          _exit(EX_OSERR);
 
1495
        }
 
1496
        ret = setenv("MODE", mode, 1);
 
1497
        if(ret == -1){
 
1498
          perror_plus("setenv");
 
1499
          _exit(EX_OSERR);
 
1500
        }
 
1501
        char *delaystring;
 
1502
        ret = asprintf(&delaystring, "%f", delay);
 
1503
        if(ret == -1){
 
1504
          perror_plus("asprintf");
 
1505
          _exit(EX_OSERR);
 
1506
        }
 
1507
        ret = setenv("DELAY", delaystring, 1);
 
1508
        if(ret == -1){
 
1509
          free(delaystring);
 
1510
          perror_plus("setenv");
 
1511
          _exit(EX_OSERR);
 
1512
        }
 
1513
        free(delaystring);
 
1514
        if(connect_to != NULL){
 
1515
          ret = setenv("CONNECT", connect_to, 1);
 
1516
          if(ret == -1){
 
1517
            perror_plus("setenv");
 
1518
            _exit(EX_OSERR);
 
1519
          }
 
1520
        }
 
1521
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1522
          perror_plus("execl");
 
1523
          _exit(EXIT_FAILURE);
 
1524
        }
 
1525
      } else {
 
1526
        int status;
 
1527
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1528
          perror_plus("waitpid");
 
1529
          free(fullname);
 
1530
          continue;
 
1531
        }
 
1532
        if(WIFEXITED(status)){
 
1533
          if(WEXITSTATUS(status) != 0){
 
1534
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1535
                         " with status %d\n", direntry->d_name,
 
1536
                         WEXITSTATUS(status));
 
1537
            free(fullname);
 
1538
            continue;
 
1539
          }
 
1540
        } else if(WIFSIGNALED(status)){
 
1541
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1542
                       " signal %d\n", direntry->d_name,
 
1543
                       WTERMSIG(status));
 
1544
          free(fullname);
 
1545
          continue;
 
1546
        } else {
 
1547
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1548
                       " crashed\n", direntry->d_name);
 
1549
          free(fullname);
 
1550
          continue;
 
1551
        }
 
1552
      }
 
1553
      free(fullname);
 
1554
      if(debug){
 
1555
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1556
                     direntry->d_name);
 
1557
      }
 
1558
    }
 
1559
    close(devnull);
 
1560
  }
 
1561
  return true;
 
1562
}
 
1563
 
 
1564
int bring_up_interface(const char * const interface, const float delay){
 
1565
  int sd = -1;
 
1566
  int old_errno = errno;
 
1567
  int ret_errno = 0;
 
1568
  int ret;
 
1569
  struct ifreq network;
 
1570
  AvahiIfIndex if_index = (AvahiIfIndex)if_nametoindex(interface);
 
1571
  if(if_index == 0){
 
1572
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1573
    errno = old_errno;
 
1574
    return ENXIO;
 
1575
  }
 
1576
  
 
1577
  if(quit_now){
 
1578
    errno = old_errno;
 
1579
    return EINTR;
 
1580
  }
 
1581
  
 
1582
  /* Re-raise priviliges */
 
1583
  raise_privileges();
 
1584
  
 
1585
#ifdef __linux__
 
1586
  /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1587
     messages about the network interface to mess up the prompt */
 
1588
  ret = klogctl(8, NULL, 5);
 
1589
  bool restore_loglevel = true;
 
1590
  if(ret == -1){
 
1591
    restore_loglevel = false;
 
1592
    perror_plus("klogctl");
 
1593
  }
 
1594
#endif  /* __linux__ */
 
1595
    
 
1596
  sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1597
  if(sd < 0){
 
1598
    ret_errno = errno;
 
1599
    perror_plus("socket");
 
1600
#ifdef __linux__
 
1601
    if(restore_loglevel){
 
1602
      ret = klogctl(7, NULL, 0);
 
1603
      if(ret == -1){
 
1604
        perror_plus("klogctl");
 
1605
      }
 
1606
    }
 
1607
#endif  /* __linux__ */
 
1608
    /* Lower privileges */
 
1609
    lower_privileges();
 
1610
    errno = old_errno;
 
1611
    return ret_errno;
 
1612
  }
 
1613
  strcpy(network.ifr_name, interface);
 
1614
  ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1615
  if(ret == -1){
 
1616
    ret_errno = errno;
 
1617
    perror_plus("ioctl SIOCGIFFLAGS");
 
1618
#ifdef __linux__
 
1619
    if(restore_loglevel){
 
1620
      ret = klogctl(7, NULL, 0);
 
1621
      if(ret == -1){
 
1622
        perror_plus("klogctl");
 
1623
      }
 
1624
    }
 
1625
#endif  /* __linux__ */
 
1626
    /* Lower privileges */
 
1627
    lower_privileges();
 
1628
    errno = old_errno;
 
1629
    return ret_errno;
 
1630
  }
 
1631
  if((network.ifr_flags & IFF_UP) == 0){
 
1632
    network.ifr_flags |= IFF_UP;
 
1633
    ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1634
    if(ret == -1){
 
1635
      ret_errno = errno;
 
1636
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1637
#ifdef __linux__
 
1638
      if(restore_loglevel){
 
1639
        ret = klogctl(7, NULL, 0);
 
1640
        if(ret == -1){
 
1641
          perror_plus("klogctl");
 
1642
        }
 
1643
      }
 
1644
#endif  /* __linux__ */
 
1645
        /* Lower privileges */
 
1646
      lower_privileges();
 
1647
      errno = old_errno;
 
1648
      return ret_errno;
 
1649
    }
 
1650
  }
 
1651
  /* Sleep checking until interface is running.
 
1652
     Check every 0.25s, up to total time of delay */
 
1653
  for(int i=0; i < delay * 4; i++){
 
1654
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1655
    if(ret == -1){
 
1656
      perror_plus("ioctl SIOCGIFFLAGS");
 
1657
    } else if(network.ifr_flags & IFF_RUNNING){
 
1658
      break;
 
1659
    }
 
1660
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1661
    ret = nanosleep(&sleeptime, NULL);
 
1662
    if(ret == -1 and errno != EINTR){
 
1663
      perror_plus("nanosleep");
 
1664
    }
 
1665
  }
 
1666
  /* Close the socket */
 
1667
  ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1668
  if(ret == -1){
 
1669
    perror_plus("close");
 
1670
  }
 
1671
#ifdef __linux__
 
1672
  if(restore_loglevel){
 
1673
    /* Restores kernel loglevel to default */
 
1674
    ret = klogctl(7, NULL, 0);
 
1675
    if(ret == -1){
 
1676
      perror_plus("klogctl");
 
1677
    }
 
1678
  }
 
1679
#endif  /* __linux__ */
 
1680
  /* Lower privileges */
 
1681
  lower_privileges();
 
1682
  errno = old_errno;
 
1683
  return 0;
 
1684
}
 
1685
 
1275
1686
int main(int argc, char *argv[]){
1276
1687
  AvahiSServiceBrowser *sb = NULL;
1277
1688
  int error;
1283
1694
  struct ifreq network;
1284
1695
  int sd = -1;
1285
1696
  bool take_down_interface = false;
1286
 
  uid_t uid;
1287
 
  gid_t gid;
1288
1697
  char tempdir[] = "/tmp/mandosXXXXXX";
1289
1698
  bool tempdir_created = false;
1290
1699
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1357
1766
        .group = 2 },
1358
1767
      { .name = "retry", .key = 132,
1359
1768
        .arg = "SECONDS",
1360
 
        .doc = "Retry interval used when denied by the mandos server",
 
1769
        .doc = "Retry interval used when denied by the Mandos server",
 
1770
        .group = 2 },
 
1771
      { .name = "network-hook-dir", .key = 133,
 
1772
        .arg = "DIR",
 
1773
        .doc = "Directory where network hooks are located",
1361
1774
        .group = 2 },
1362
1775
      /*
1363
1776
       * These reproduce what we would get without ARGP_NO_HELP
1417
1830
          argp_error(state, "Bad retry interval");
1418
1831
        }
1419
1832
        break;
 
1833
      case 133:                 /* --network-hook-dir */
 
1834
        hookdir = arg;
 
1835
        break;
1420
1836
        /*
1421
1837
         * These reproduce what we would get without ARGP_NO_HELP
1422
1838
         */
1428
1844
        argp_state_help(state, state->out_stream,
1429
1845
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1430
1846
      case 'V':                 /* --version */
1431
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1847
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1432
1848
        exit(argp_err_exit_status);
1433
1849
        break;
1434
1850
      default:
1461
1877
  {
1462
1878
    /* Work around Debian bug #633582:
1463
1879
       <http://bugs.debian.org/633582> */
1464
 
    struct stat st;
1465
1880
    
1466
1881
    /* Re-raise priviliges */
1467
 
    errno = 0;
1468
 
    ret = seteuid(0);
1469
 
    if(ret == -1){
1470
 
      perror_plus("seteuid");
1471
 
    }
1472
 
    
1473
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1474
 
      int seckey_fd = open(seckey, O_RDONLY);
1475
 
      if(seckey_fd == -1){
1476
 
        perror_plus("open");
1477
 
      } else {
1478
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1479
 
        if(ret == -1){
1480
 
          perror_plus("fstat");
1481
 
        } else {
1482
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1483
 
            ret = fchown(seckey_fd, uid, gid);
1484
 
            if(ret == -1){
1485
 
              perror_plus("fchown");
1486
 
            }
1487
 
          }
1488
 
        }
1489
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1490
 
      }
1491
 
    }
1492
 
    
1493
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1494
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1495
 
      if(pubkey_fd == -1){
1496
 
        perror_plus("open");
1497
 
      } else {
1498
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1499
 
        if(ret == -1){
1500
 
          perror_plus("fstat");
1501
 
        } else {
1502
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1503
 
            ret = fchown(pubkey_fd, uid, gid);
1504
 
            if(ret == -1){
1505
 
              perror_plus("fchown");
1506
 
            }
1507
 
          }
1508
 
        }
1509
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1510
 
      }
1511
 
    }
1512
 
    
1513
 
    /* Lower privileges */
1514
 
    errno = 0;
1515
 
    ret = seteuid(uid);
1516
 
    if(ret == -1){
1517
 
      perror_plus("seteuid");
1518
 
    }
 
1882
    if(raise_privileges() == 0){
 
1883
      struct stat st;
 
1884
      
 
1885
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1886
        int seckey_fd = open(seckey, O_RDONLY);
 
1887
        if(seckey_fd == -1){
 
1888
          perror_plus("open");
 
1889
        } else {
 
1890
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1891
          if(ret == -1){
 
1892
            perror_plus("fstat");
 
1893
          } else {
 
1894
            if(S_ISREG(st.st_mode)
 
1895
               and st.st_uid == 0 and st.st_gid == 0){
 
1896
              ret = fchown(seckey_fd, uid, gid);
 
1897
              if(ret == -1){
 
1898
                perror_plus("fchown");
 
1899
              }
 
1900
            }
 
1901
          }
 
1902
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1903
        }
 
1904
      }
 
1905
    
 
1906
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1907
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1908
        if(pubkey_fd == -1){
 
1909
          perror_plus("open");
 
1910
        } else {
 
1911
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1912
          if(ret == -1){
 
1913
            perror_plus("fstat");
 
1914
          } else {
 
1915
            if(S_ISREG(st.st_mode)
 
1916
               and st.st_uid == 0 and st.st_gid == 0){
 
1917
              ret = fchown(pubkey_fd, uid, gid);
 
1918
              if(ret == -1){
 
1919
                perror_plus("fchown");
 
1920
              }
 
1921
            }
 
1922
          }
 
1923
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1924
        }
 
1925
      }
 
1926
    
 
1927
      /* Lower privileges */
 
1928
      errno = 0;
 
1929
      ret = seteuid(uid);
 
1930
      if(ret == -1){
 
1931
        perror_plus("seteuid");
 
1932
      }
 
1933
    }
 
1934
  }
 
1935
  
 
1936
  /* Run network hooks */
 
1937
  if(not run_network_hooks("start", interface, delay)){
 
1938
    goto end;
1519
1939
  }
1520
1940
  
1521
1941
  if(not debug){
1522
1942
    avahi_set_log_function(empty_log);
1523
1943
  }
1524
 
 
 
1944
  
1525
1945
  if(interface[0] == '\0'){
1526
1946
    struct dirent **direntries;
1527
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1947
    /* First look for interfaces that are up */
 
1948
    ret = scandir(sys_class_net, &direntries, up_interface,
1528
1949
                  alphasort);
 
1950
    if(ret == 0){
 
1951
      /* No up interfaces, look for any good interfaces */
 
1952
      free(direntries);
 
1953
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1954
                    alphasort);
 
1955
    }
1529
1956
    if(ret >= 1){
1530
 
      /* Pick the first good interface */
 
1957
      /* Pick the first interface returned */
1531
1958
      interface = strdup(direntries[0]->d_name);
1532
1959
      if(debug){
1533
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1960
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1534
1961
      }
1535
1962
      if(interface == NULL){
1536
1963
        perror_plus("malloc");
1541
1968
      free(direntries);
1542
1969
    } else {
1543
1970
      free(direntries);
1544
 
      fprintf(stderr, "Could not find a network interface\n");
 
1971
      fprintf_plus(stderr, "Could not find a network interface\n");
1545
1972
      exitcode = EXIT_FAILURE;
1546
1973
      goto end;
1547
1974
    }
1553
1980
  srand((unsigned int) time(NULL));
1554
1981
  mc.simple_poll = avahi_simple_poll_new();
1555
1982
  if(mc.simple_poll == NULL){
1556
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1983
    fprintf_plus(stderr,
 
1984
                 "Avahi: Failed to create simple poll object.\n");
1557
1985
    exitcode = EX_UNAVAILABLE;
1558
1986
    goto end;
1559
1987
  }
1622
2050
  }
1623
2051
  
1624
2052
  /* If the interface is down, bring it up */
1625
 
  if(strcmp(interface, "none") != 0){
1626
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1627
 
    if(if_index == 0){
1628
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1629
 
      exitcode = EX_UNAVAILABLE;
1630
 
      goto end;
1631
 
    }
1632
 
    
1633
 
    if(quit_now){
1634
 
      goto end;
1635
 
    }
1636
 
    
1637
 
    /* Re-raise priviliges */
1638
 
    errno = 0;
1639
 
    ret = seteuid(0);
1640
 
    if(ret == -1){
1641
 
      perror_plus("seteuid");
1642
 
    }
1643
 
    
1644
 
#ifdef __linux__
1645
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1646
 
       messages about the network interface to mess up the prompt */
1647
 
    ret = klogctl(8, NULL, 5);
1648
 
    bool restore_loglevel = true;
1649
 
    if(ret == -1){
1650
 
      restore_loglevel = false;
1651
 
      perror_plus("klogctl");
1652
 
    }
1653
 
#endif  /* __linux__ */
1654
 
    
1655
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1656
 
    if(sd < 0){
1657
 
      perror_plus("socket");
1658
 
      exitcode = EX_OSERR;
1659
 
#ifdef __linux__
1660
 
      if(restore_loglevel){
1661
 
        ret = klogctl(7, NULL, 0);
1662
 
        if(ret == -1){
1663
 
          perror_plus("klogctl");
1664
 
        }
1665
 
      }
1666
 
#endif  /* __linux__ */
1667
 
      /* Lower privileges */
1668
 
      errno = 0;
1669
 
      ret = seteuid(uid);
1670
 
      if(ret == -1){
1671
 
        perror_plus("seteuid");
1672
 
      }
1673
 
      goto end;
1674
 
    }
1675
 
    strcpy(network.ifr_name, interface);
1676
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1677
 
    if(ret == -1){
1678
 
      perror_plus("ioctl SIOCGIFFLAGS");
1679
 
#ifdef __linux__
1680
 
      if(restore_loglevel){
1681
 
        ret = klogctl(7, NULL, 0);
1682
 
        if(ret == -1){
1683
 
          perror_plus("klogctl");
1684
 
        }
1685
 
      }
1686
 
#endif  /* __linux__ */
1687
 
      exitcode = EX_OSERR;
1688
 
      /* Lower privileges */
1689
 
      errno = 0;
1690
 
      ret = seteuid(uid);
1691
 
      if(ret == -1){
1692
 
        perror_plus("seteuid");
1693
 
      }
1694
 
      goto end;
1695
 
    }
1696
 
    if((network.ifr_flags & IFF_UP) == 0){
1697
 
      network.ifr_flags |= IFF_UP;
1698
 
      take_down_interface = true;
1699
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1700
 
      if(ret == -1){
1701
 
        take_down_interface = false;
1702
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1703
 
        exitcode = EX_OSERR;
1704
 
#ifdef __linux__
1705
 
        if(restore_loglevel){
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
 
        ret = seteuid(uid);
1715
 
        if(ret == -1){
1716
 
          perror_plus("seteuid");
1717
 
        }
1718
 
        goto end;
1719
 
      }
1720
 
    }
1721
 
    /* Sleep checking until interface is running.
1722
 
       Check every 0.25s, up to total time of delay */
1723
 
    for(int i=0; i < delay * 4; i++){
1724
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1725
 
      if(ret == -1){
1726
 
        perror_plus("ioctl SIOCGIFFLAGS");
1727
 
      } else if(network.ifr_flags & IFF_RUNNING){
1728
 
        break;
1729
 
      }
1730
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1731
 
      ret = nanosleep(&sleeptime, NULL);
1732
 
      if(ret == -1 and errno != EINTR){
1733
 
        perror_plus("nanosleep");
1734
 
      }
1735
 
    }
1736
 
    if(not take_down_interface){
1737
 
      /* We won't need the socket anymore */
1738
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1739
 
      if(ret == -1){
1740
 
        perror_plus("close");
1741
 
      }
1742
 
    }
1743
 
#ifdef __linux__
1744
 
    if(restore_loglevel){
1745
 
      /* Restores kernel loglevel to default */
1746
 
      ret = klogctl(7, NULL, 0);
1747
 
      if(ret == -1){
1748
 
        perror_plus("klogctl");
1749
 
      }
1750
 
    }
1751
 
#endif  /* __linux__ */
1752
 
    /* Lower privileges */
1753
 
    errno = 0;
1754
 
    if(take_down_interface){
1755
 
      /* Lower privileges */
1756
 
      ret = seteuid(uid);
1757
 
      if(ret == -1){
1758
 
        perror_plus("seteuid");
1759
 
      }
1760
 
    } else {
1761
 
      /* Lower privileges permanently */
1762
 
      ret = setuid(uid);
1763
 
      if(ret == -1){
1764
 
        perror_plus("setuid");
1765
 
      }
 
2053
  if((interface[0] != '\0') and (strcmp(interface, "none") != 0)){
 
2054
    ret = bring_up_interface(interface, delay);
 
2055
    if(ret != 0){
 
2056
      errno = ret;
 
2057
      perror_plus("Failed to bring up interface");
1766
2058
    }
1767
2059
  }
1768
2060
  
1772
2064
  
1773
2065
  ret = init_gnutls_global(pubkey, seckey);
1774
2066
  if(ret == -1){
1775
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2067
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1776
2068
    exitcode = EX_UNAVAILABLE;
1777
2069
    goto end;
1778
2070
  } else {
1794
2086
  }
1795
2087
  
1796
2088
  if(not init_gpgme(pubkey, seckey, tempdir)){
1797
 
    fprintf(stderr, "init_gpgme failed\n");
 
2089
    fprintf_plus(stderr, "init_gpgme failed\n");
1798
2090
    exitcode = EX_UNAVAILABLE;
1799
2091
    goto end;
1800
2092
  } else {
1809
2101
    /* Connect directly, do not use Zeroconf */
1810
2102
    /* (Mainly meant for debugging) */
1811
2103
    char *address = strrchr(connect_to, ':');
 
2104
    
1812
2105
    if(address == NULL){
1813
 
      fprintf(stderr, "No colon in address\n");
 
2106
      fprintf_plus(stderr, "No colon in address\n");
1814
2107
      exitcode = EX_USAGE;
1815
2108
      goto end;
1816
2109
    }
1824
2117
    tmpmax = strtoimax(address+1, &tmp, 10);
1825
2118
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1826
2119
       or tmpmax != (uint16_t)tmpmax){
1827
 
      fprintf(stderr, "Bad port number\n");
 
2120
      fprintf_plus(stderr, "Bad port number\n");
1828
2121
      exitcode = EX_USAGE;
1829
2122
      goto end;
1830
2123
    }
1860
2153
        break;
1861
2154
      }
1862
2155
      if(debug){
1863
 
        fprintf(stderr, "Retrying in %d seconds\n",
1864
 
                (int)retry_interval);
 
2156
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2157
                     (int)retry_interval);
1865
2158
      }
1866
2159
      sleep((int)retry_interval);
1867
2160
    }
1869
2162
    if (not quit_now){
1870
2163
      exitcode = EXIT_SUCCESS;
1871
2164
    }
1872
 
 
 
2165
    
1873
2166
    goto end;
1874
2167
  }
1875
2168
  
1897
2190
  
1898
2191
  /* Check if creating the Avahi server object succeeded */
1899
2192
  if(mc.server == NULL){
1900
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1901
 
            avahi_strerror(error));
 
2193
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2194
                 avahi_strerror(error));
1902
2195
    exitcode = EX_UNAVAILABLE;
1903
2196
    goto end;
1904
2197
  }
1912
2205
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1913
2206
                                   NULL, 0, browse_callback, NULL);
1914
2207
  if(sb == NULL){
1915
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1916
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2208
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2209
                 avahi_strerror(avahi_server_errno(mc.server)));
1917
2210
    exitcode = EX_UNAVAILABLE;
1918
2211
    goto end;
1919
2212
  }
1925
2218
  /* Run the main loop */
1926
2219
  
1927
2220
  if(debug){
1928
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2221
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1929
2222
  }
1930
2223
 
1931
2224
  ret = avahi_loop_with_timeout(mc.simple_poll,
1932
2225
                                (int)(retry_interval * 1000));
1933
2226
  if(debug){
1934
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1935
 
            (ret == 0) ? "successfully" : "with error");
 
2227
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2228
                 (ret == 0) ? "successfully" : "with error");
1936
2229
  }
1937
2230
  
1938
2231
 end:
1939
2232
  
1940
2233
  if(debug){
1941
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2234
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1942
2235
  }
1943
2236
  
1944
2237
  /* Cleanup things */
1960
2253
  if(gpgme_initialized){
1961
2254
    gpgme_release(mc.ctx);
1962
2255
  }
1963
 
 
 
2256
  
1964
2257
  /* Cleans up the circular linked list of Mandos servers the client
1965
2258
     has seen */
1966
2259
  if(mc.current_server != NULL){
1972
2265
    }
1973
2266
  }
1974
2267
  
1975
 
  /* Take down the network interface */
1976
 
  if(take_down_interface){
1977
 
    /* Re-raise priviliges */
1978
 
    errno = 0;
1979
 
    ret = seteuid(0);
1980
 
    if(ret == -1){
1981
 
      perror_plus("seteuid");
1982
 
    }
1983
 
    if(geteuid() == 0){
 
2268
  /* Run network hooks */
 
2269
  run_network_hooks("stop", interface, delay);
 
2270
  
 
2271
  /* Re-raise priviliges */
 
2272
  {
 
2273
    raise_privileges();
 
2274
    
 
2275
    /* Take down the network interface */
 
2276
    if(take_down_interface and geteuid() == 0){
1984
2277
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1985
2278
      if(ret == -1){
1986
2279
        perror_plus("ioctl SIOCGIFFLAGS");
1987
 
      } else if(network.ifr_flags & IFF_UP) {
 
2280
      } else if(network.ifr_flags & IFF_UP){
1988
2281
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1989
2282
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1990
2283
        if(ret == -1){
1995
2288
      if(ret == -1){
1996
2289
        perror_plus("close");
1997
2290
      }
1998
 
      /* Lower privileges permanently */
1999
 
      errno = 0;
2000
 
      ret = setuid(uid);
2001
 
      if(ret == -1){
2002
 
        perror_plus("setuid");
2003
 
      }
2004
2291
    }
2005
2292
  }
 
2293
  /* Lower privileges permanently */
 
2294
  errno = 0;
 
2295
  ret = setuid(uid);
 
2296
  if(ret == -1){
 
2297
    perror_plus("setuid");
 
2298
  }
2006
2299
  
2007
2300
  /* Removes the GPGME temp directory and all files inside */
2008
2301
  if(tempdir_created){
2022
2315
        }
2023
2316
        ret = remove(fullname);
2024
2317
        if(ret == -1){
2025
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2026
 
                  strerror(errno));
 
2318
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2319
                       strerror(errno));
2027
2320
        }
2028
2321
        free(fullname);
2029
2322
      }