/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Björn Påhlsson
  • Date: 2011-11-27 19:51:00 UTC
  • mto: (518.2.5 persistent-state-gpgme)
  • mto: This revision was merged to the branch mainline in revision 524.
  • Revision ID: belorn@recompile.se-20111127195100-fx0mpeia9xihvpmd
renamed variables

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
 
76
                                   setgid(), pause() */
77
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
 
#include <grp.h>                /* setgroups() */
91
88
 
92
89
#ifdef __linux__
93
90
#include <sys/klog.h>           /* klogctl() */
111
108
                                   init_gnutls_session(),
112
109
                                   GNUTLS_* */
113
110
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
 
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
113
 
117
114
/* GPGME */
118
115
#include <gpgme.h>              /* All GPGME types, constants and
126
123
#define PATHDIR "/conf/conf.d/mandos"
127
124
#define SECKEY "seckey.txt"
128
125
#define PUBKEY "pubkey.txt"
129
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
130
126
 
131
127
bool debug = false;
132
128
static const char mandos_protocol_version[] = "1";
134
130
const char *argp_program_bug_address = "<mandos@recompile.se>";
135
131
static const char sys_class_net[] = "/sys/class/net";
136
132
char *connect_to = NULL;
137
 
const char *hookdir = HOOKDIR;
138
 
uid_t uid = 65534;
139
 
gid_t gid = 65534;
140
133
 
141
134
/* Doubly linked list that need to be circularly linked when used */
142
135
typedef struct server{
172
165
 
173
166
/* Function to use when printing errors */
174
167
void perror_plus(const char *print_text){
175
 
  int e = errno;
176
168
  fprintf(stderr, "Mandos plugin %s: ",
177
169
          program_invocation_short_name);
178
 
  errno = e;
179
170
  perror(print_text);
180
171
}
181
172
 
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
 
 
192
173
/*
193
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
194
175
 * bytes. "buffer_capacity" is how much is currently allocated,
195
176
 * "buffer_length" is how much is already used.
196
177
 */
197
178
size_t incbuffer(char **buffer, size_t buffer_length,
198
 
                 size_t buffer_capacity){
 
179
                  size_t buffer_capacity){
199
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
200
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
201
182
    if(buffer == NULL){
207
188
}
208
189
 
209
190
/* Add server to set of servers to retry periodically */
210
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
211
 
                int af){
 
191
int add_server(const char *ip, uint16_t port,
 
192
                 AvahiIfIndex if_index,
 
193
                 int af){
212
194
  int ret;
213
195
  server *new_server = malloc(sizeof(server));
214
196
  if(new_server == NULL){
215
197
    perror_plus("malloc");
216
 
    return false;
 
198
    return -1;
217
199
  }
218
200
  *new_server = (server){ .ip = strdup(ip),
219
 
                          .port = port,
220
 
                          .if_index = if_index,
221
 
                          .af = af };
 
201
                         .port = port,
 
202
                         .if_index = if_index,
 
203
                         .af = af };
222
204
  if(new_server->ip == NULL){
223
205
    perror_plus("strdup");
224
 
    return false;
 
206
    return -1;
225
207
  }
226
208
  /* Special case of first server */
227
209
  if (mc.current_server == NULL){
238
220
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
239
221
  if(ret == -1){
240
222
    perror_plus("clock_gettime");
241
 
    return false;
 
223
    return -1;
242
224
  }
243
 
  return true;
 
225
  return 0;
244
226
}
245
227
 
246
228
/* 
247
229
 * Initialize GPGME.
248
230
 */
249
 
static bool init_gpgme(const char *seckey, const char *pubkey,
250
 
                       const char *tempdir){
 
231
static bool init_gpgme(const char *seckey,
 
232
                       const char *pubkey, const char *tempdir){
251
233
  gpgme_error_t rc;
252
234
  gpgme_engine_info_t engine_info;
253
235
  
268
250
    
269
251
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
270
252
    if(rc != GPG_ERR_NO_ERROR){
271
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
272
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
253
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
254
              gpgme_strsource(rc), gpgme_strerror(rc));
273
255
      return false;
274
256
    }
275
257
    
276
258
    rc = gpgme_op_import(mc.ctx, pgp_data);
277
259
    if(rc != GPG_ERR_NO_ERROR){
278
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
279
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
260
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
261
              gpgme_strsource(rc), gpgme_strerror(rc));
280
262
      return false;
281
263
    }
282
264
    
289
271
  }
290
272
  
291
273
  if(debug){
292
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
274
    fprintf(stderr, "Initializing GPGME\n");
293
275
  }
294
276
  
295
277
  /* Init GPGME */
296
278
  gpgme_check_version(NULL);
297
279
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
298
280
  if(rc != GPG_ERR_NO_ERROR){
299
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
300
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
281
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
282
            gpgme_strsource(rc), gpgme_strerror(rc));
301
283
    return false;
302
284
  }
303
285
  
304
286
  /* Set GPGME home directory for the OpenPGP engine only */
305
287
  rc = gpgme_get_engine_info(&engine_info);
306
288
  if(rc != GPG_ERR_NO_ERROR){
307
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
308
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
289
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
290
            gpgme_strsource(rc), gpgme_strerror(rc));
309
291
    return false;
310
292
  }
311
293
  while(engine_info != NULL){
317
299
    engine_info = engine_info->next;
318
300
  }
319
301
  if(engine_info == NULL){
320
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
321
 
                 tempdir);
 
302
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
322
303
    return false;
323
304
  }
324
305
  
325
306
  /* Create new GPGME "context" */
326
307
  rc = gpgme_new(&(mc.ctx));
327
308
  if(rc != GPG_ERR_NO_ERROR){
328
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
329
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
330
 
                 gpgme_strerror(rc));
 
309
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
310
            gpgme_strsource(rc), gpgme_strerror(rc));
331
311
    return false;
332
312
  }
333
313
  
352
332
  ssize_t plaintext_length = 0;
353
333
  
354
334
  if(debug){
355
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
335
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
356
336
  }
357
337
  
358
338
  /* Create new GPGME data buffer from memory cryptotext */
359
339
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
360
340
                               0);
361
341
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
363
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
342
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
343
            gpgme_strsource(rc), gpgme_strerror(rc));
364
344
    return -1;
365
345
  }
366
346
  
367
347
  /* Create new empty GPGME data buffer for the plaintext */
368
348
  rc = gpgme_data_new(&dh_plain);
369
349
  if(rc != GPG_ERR_NO_ERROR){
370
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
371
 
                 "bad gpgme_data_new: %s: %s\n",
372
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
350
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
351
            gpgme_strsource(rc), gpgme_strerror(rc));
373
352
    gpgme_data_release(dh_crypto);
374
353
    return -1;
375
354
  }
378
357
     data buffer */
379
358
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
380
359
  if(rc != GPG_ERR_NO_ERROR){
381
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
382
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
360
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
361
            gpgme_strsource(rc), gpgme_strerror(rc));
383
362
    plaintext_length = -1;
384
363
    if(debug){
385
364
      gpgme_decrypt_result_t result;
386
365
      result = gpgme_op_decrypt_result(mc.ctx);
387
366
      if(result == NULL){
388
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
367
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
389
368
      } else {
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);
 
369
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
370
                result->unsupported_algorithm);
 
371
        fprintf(stderr, "Wrong key usage: %u\n",
 
372
                result->wrong_key_usage);
394
373
        if(result->file_name != NULL){
395
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
374
          fprintf(stderr, "File name: %s\n", result->file_name);
396
375
        }
397
376
        gpgme_recipient_t recipient;
398
377
        recipient = result->recipients;
399
378
        while(recipient != NULL){
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");
 
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");
407
385
          recipient = recipient->next;
408
386
        }
409
387
      }
412
390
  }
413
391
  
414
392
  if(debug){
415
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
393
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
416
394
  }
417
395
  
418
396
  /* Seek back to the beginning of the GPGME plaintext data buffer */
425
403
  *plaintext = NULL;
426
404
  while(true){
427
405
    plaintext_capacity = incbuffer(plaintext,
428
 
                                   (size_t)plaintext_length,
429
 
                                   plaintext_capacity);
 
406
                                      (size_t)plaintext_length,
 
407
                                      plaintext_capacity);
430
408
    if(plaintext_capacity == 0){
431
 
      perror_plus("incbuffer");
432
 
      plaintext_length = -1;
433
 
      goto decrypt_end;
 
409
        perror_plus("incbuffer");
 
410
        plaintext_length = -1;
 
411
        goto decrypt_end;
434
412
    }
435
413
    
436
414
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
449
427
  }
450
428
  
451
429
  if(debug){
452
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
430
    fprintf(stderr, "Decrypted password is: ");
453
431
    for(ssize_t i = 0; i < plaintext_length; i++){
454
432
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
455
433
    }
477
455
/* GnuTLS log function callback */
478
456
static void debuggnutls(__attribute__((unused)) int level,
479
457
                        const char* string){
480
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
458
  fprintf(stderr, "GnuTLS: %s", string);
481
459
}
482
460
 
483
461
static int init_gnutls_global(const char *pubkeyfilename,
485
463
  int ret;
486
464
  
487
465
  if(debug){
488
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
466
    fprintf(stderr, "Initializing GnuTLS\n");
489
467
  }
490
468
  
491
469
  ret = gnutls_global_init();
492
470
  if(ret != GNUTLS_E_SUCCESS){
493
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
494
 
                 safer_gnutls_strerror(ret));
 
471
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
472
            safer_gnutls_strerror(ret));
495
473
    return -1;
496
474
  }
497
475
  
506
484
  /* OpenPGP credentials */
507
485
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
508
486
  if(ret != GNUTLS_E_SUCCESS){
509
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
510
 
                 safer_gnutls_strerror(ret));
 
487
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
488
            safer_gnutls_strerror(ret));
511
489
    gnutls_global_deinit();
512
490
    return -1;
513
491
  }
514
492
  
515
493
  if(debug){
516
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
517
 
                 " secret key %s as GnuTLS credentials\n",
518
 
                 pubkeyfilename,
519
 
                 seckeyfilename);
 
494
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
495
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
496
            seckeyfilename);
520
497
  }
521
498
  
522
499
  ret = gnutls_certificate_set_openpgp_key_file
523
500
    (mc.cred, pubkeyfilename, seckeyfilename,
524
501
     GNUTLS_OPENPGP_FMT_BASE64);
525
502
  if(ret != GNUTLS_E_SUCCESS){
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));
 
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));
531
508
    goto globalfail;
532
509
  }
533
510
  
534
511
  /* GnuTLS server initialization */
535
512
  ret = gnutls_dh_params_init(&mc.dh_params);
536
513
  if(ret != GNUTLS_E_SUCCESS){
537
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
538
 
                 " initialization: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
514
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
515
            " %s\n", safer_gnutls_strerror(ret));
540
516
    goto globalfail;
541
517
  }
542
518
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
543
519
  if(ret != GNUTLS_E_SUCCESS){
544
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
545
 
                 safer_gnutls_strerror(ret));
 
520
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
521
            safer_gnutls_strerror(ret));
546
522
    goto globalfail;
547
523
  }
548
524
  
568
544
    }
569
545
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
570
546
  if(ret != GNUTLS_E_SUCCESS){
571
 
    fprintf_plus(stderr,
572
 
                 "Error in GnuTLS session initialization: %s\n",
573
 
                 safer_gnutls_strerror(ret));
 
547
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
548
            safer_gnutls_strerror(ret));
574
549
  }
575
550
  
576
551
  {
583
558
      }
584
559
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
585
560
    if(ret != GNUTLS_E_SUCCESS){
586
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
587
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
588
 
                   safer_gnutls_strerror(ret));
 
561
      fprintf(stderr, "Syntax error at: %s\n", err);
 
562
      fprintf(stderr, "GnuTLS error: %s\n",
 
563
              safer_gnutls_strerror(ret));
589
564
      gnutls_deinit(*session);
590
565
      return -1;
591
566
    }
600
575
    }
601
576
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
602
577
  if(ret != GNUTLS_E_SUCCESS){
603
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
604
 
                 safer_gnutls_strerror(ret));
 
578
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
579
            safer_gnutls_strerror(ret));
605
580
    gnutls_deinit(*session);
606
581
    return -1;
607
582
  }
652
627
    pf = PF_INET;
653
628
    break;
654
629
  default:
655
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
630
    fprintf(stderr, "Bad address family: %d\n", af);
656
631
    errno = EINVAL;
657
632
    return -1;
658
633
  }
663
638
  }
664
639
  
665
640
  if(debug){
666
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
667
 
                 PRIu16 "\n", ip, port);
 
641
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
642
            "\n", ip, port);
668
643
  }
669
644
  
670
645
  tcp_sd = socket(pf, SOCK_STREAM, 0);
696
671
  }
697
672
  if(ret == 0){
698
673
    int e = errno;
699
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
674
    fprintf(stderr, "Bad address: %s\n", ip);
700
675
    errno = e;
701
676
    goto mandos_end;
702
677
  }
707
682
    
708
683
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
709
684
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
710
 
                                -Wunreachable-code*/
 
685
                              -Wunreachable-code*/
711
686
      if(if_index == AVAHI_IF_UNSPEC){
712
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
713
 
                     " incomplete without a network interface\n");
 
687
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
688
                " without a network interface\n");
714
689
        errno = EINVAL;
715
690
        goto mandos_end;
716
691
      }
734
709
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
735
710
        perror_plus("if_indextoname");
736
711
      } else {
737
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
738
 
                     "\n", ip, interface, port);
 
712
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
713
                ip, interface, port);
739
714
      }
740
715
    } else {
741
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
742
 
                   ip, port);
 
716
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
717
              port);
743
718
    }
744
719
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
745
720
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
755
730
      perror_plus("inet_ntop");
756
731
    } else {
757
732
      if(strcmp(addrstr, ip) != 0){
758
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
733
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
759
734
      }
760
735
    }
761
736
  }
789
764
  while(true){
790
765
    size_t out_size = strlen(out);
791
766
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
792
 
                                        out_size - written));
 
767
                                   out_size - written));
793
768
    if(ret == -1){
794
769
      int e = errno;
795
770
      perror_plus("write");
815
790
  }
816
791
  
817
792
  if(debug){
818
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
793
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
819
794
  }
820
795
  
821
796
  if(quit_now){
823
798
    goto mandos_end;
824
799
  }
825
800
  
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);
 
801
  /* Spurious warning from -Wint-to-pointer-cast */
 
802
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
831
803
  
832
804
  if(quit_now){
833
805
    errno = EINTR;
844
816
  
845
817
  if(ret != GNUTLS_E_SUCCESS){
846
818
    if(debug){
847
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
819
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
848
820
      gnutls_perror(ret);
849
821
    }
850
822
    errno = EPROTO;
854
826
  /* Read OpenPGP packet that contains the wanted password */
855
827
  
856
828
  if(debug){
857
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
858
 
                 " %s\n", ip);
 
829
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
830
            ip);
859
831
  }
860
832
  
861
833
  while(true){
866
838
    }
867
839
    
868
840
    buffer_capacity = incbuffer(&buffer, buffer_length,
869
 
                                buffer_capacity);
 
841
                                   buffer_capacity);
870
842
    if(buffer_capacity == 0){
871
843
      int e = errno;
872
844
      perror_plus("incbuffer");
899
871
          }
900
872
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
901
873
        if(ret < 0){
902
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
903
 
                       "***\n");
 
874
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
904
875
          gnutls_perror(ret);
905
876
          errno = EPROTO;
906
877
          goto mandos_end;
907
878
        }
908
879
        break;
909
880
      default:
910
 
        fprintf_plus(stderr, "Unknown error while reading data from"
911
 
                     " encrypted session with Mandos server\n");
 
881
        fprintf(stderr, "Unknown error while reading data from"
 
882
                " encrypted session with Mandos server\n");
912
883
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
913
884
        errno = EIO;
914
885
        goto mandos_end;
919
890
  }
920
891
  
921
892
  if(debug){
922
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
893
    fprintf(stderr, "Closing TLS session\n");
923
894
  }
924
895
  
925
896
  if(quit_now){
937
908
  
938
909
  if(buffer_length > 0){
939
910
    ssize_t decrypted_buffer_size;
940
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
911
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
912
                                               buffer_length,
941
913
                                               &decrypted_buffer);
942
914
    if(decrypted_buffer_size >= 0){
943
915
      
954
926
        if(ret == 0 and ferror(stdout)){
955
927
          int e = errno;
956
928
          if(debug){
957
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
958
 
                         strerror(errno));
 
929
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
930
                    strerror(errno));
959
931
          }
960
932
          errno = e;
961
933
          goto mandos_end;
1018
990
  switch(event){
1019
991
  default:
1020
992
  case AVAHI_RESOLVER_FAILURE:
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)));
 
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)));
1025
996
    break;
1026
997
    
1027
998
  case AVAHI_RESOLVER_FOUND:
1029
1000
      char ip[AVAHI_ADDRESS_STR_MAX];
1030
1001
      avahi_address_snprint(ip, sizeof(ip), address);
1031
1002
      if(debug){
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);
 
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);
1035
1006
      }
1036
1007
      int ret = start_mandos_communication(ip, port, interface,
1037
1008
                                           avahi_proto_to_af(proto));
1038
1009
      if(ret == 0){
1039
1010
        avahi_simple_poll_quit(mc.simple_poll);
1040
1011
      } else {
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
 
        }
 
1012
        ret = add_server(ip, port, interface,
 
1013
                         avahi_proto_to_af(proto));
1046
1014
      }
1047
1015
    }
1048
1016
  }
1072
1040
  default:
1073
1041
  case AVAHI_BROWSER_FAILURE:
1074
1042
    
1075
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1076
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1043
    fprintf(stderr, "(Avahi browser) %s\n",
 
1044
            avahi_strerror(avahi_server_errno(mc.server)));
1077
1045
    avahi_simple_poll_quit(mc.simple_poll);
1078
1046
    return;
1079
1047
    
1086
1054
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1087
1055
                                    name, type, domain, protocol, 0,
1088
1056
                                    resolve_callback, NULL) == NULL)
1089
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1090
 
                   " %s\n", name,
1091
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1057
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1058
              name, avahi_strerror(avahi_server_errno(mc.server)));
1092
1059
    break;
1093
1060
    
1094
1061
  case AVAHI_BROWSER_REMOVE:
1097
1064
  case AVAHI_BROWSER_ALL_FOR_NOW:
1098
1065
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1099
1066
    if(debug){
1100
 
      fprintf_plus(stderr, "No Mandos server found, still"
1101
 
                   " searching...\n");
 
1067
      fprintf(stderr, "No Mandos server found, still searching...\n");
1102
1068
    }
1103
1069
    break;
1104
1070
  }
1119
1085
  errno = old_errno;
1120
1086
}
1121
1087
 
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){
 
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){
1133
1144
    if(debug){
1134
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1145
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1146
              flagstring, if_entry->d_name);
1135
1147
    }
1136
 
    return false;
 
1148
    free(flagstring);
 
1149
    return 0;
1137
1150
  }
1138
 
  return true;
1139
 
}
1140
 
 
1141
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1142
 
  
 
1151
  free(flagstring);
 
1152
  ifreq_flags flags = (ifreq_flags)tmpmax;
1143
1153
  /* Reject the loopback device */
1144
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1154
  if(flags & IFF_LOOPBACK){
1145
1155
    if(debug){
1146
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1147
 
                   ifname);
 
1156
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1157
              if_entry->d_name);
1148
1158
    }
1149
 
    return false;
 
1159
    return 0;
1150
1160
  }
1151
1161
  /* Accept point-to-point devices only if connect_to is specified */
1152
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1162
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1153
1163
    if(debug){
1154
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1155
 
                   " \"%s\"\n", ifname);
 
1164
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1165
              if_entry->d_name);
1156
1166
    }
1157
 
    return true;
 
1167
    return 1;
1158
1168
  }
1159
1169
  /* Otherwise, reject non-broadcast-capable devices */
1160
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1170
  if(not (flags & IFF_BROADCAST)){
1161
1171
    if(debug){
1162
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1163
 
                   " \"%s\"\n", ifname);
 
1172
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1173
              if_entry->d_name);
1164
1174
    }
1165
 
    return false;
 
1175
    return 0;
1166
1176
  }
1167
1177
  /* Reject non-ARP interfaces (including dummy interfaces) */
1168
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1178
  if(flags & IFF_NOARP){
1169
1179
    if(debug){
1170
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1171
 
                   ifname);
 
1180
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1181
              if_entry->d_name);
1172
1182
    }
1173
 
    return false;
 
1183
    return 0;
1174
1184
  }
1175
 
  
1176
1185
  /* Accept this device */
1177
1186
  if(debug){
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;
 
1187
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1188
            if_entry->d_name);
1247
1189
  }
1248
1190
  return 1;
1249
1191
}
1259
1201
  return 1;
1260
1202
}
1261
1203
 
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
 
 
1323
1204
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1324
1205
  int ret;
1325
1206
  struct timespec now;
1329
1210
  while(true){
1330
1211
    if(mc.current_server == NULL){
1331
1212
      if (debug){
1332
 
        fprintf_plus(stderr, "Wait until first server is found."
1333
 
                     " No timeout!\n");
 
1213
        fprintf(stderr,
 
1214
                "Wait until first server is found. No timeout!\n");
1334
1215
      }
1335
1216
      ret = avahi_simple_poll_iterate(s, -1);
1336
1217
    } else {
1337
1218
      if (debug){
1338
 
        fprintf_plus(stderr, "Check current_server if we should run"
1339
 
                     " it, or wait\n");
 
1219
        fprintf(stderr, "Check current_server if we should run it,"
 
1220
                " or wait\n");
1340
1221
      }
1341
1222
      /* the current time */
1342
1223
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1358
1239
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1359
1240
      
1360
1241
      if (debug){
1361
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1362
 
                     block_time);
 
1242
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1363
1243
      }
1364
1244
      
1365
1245
      if(block_time <= 0){
1385
1265
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1386
1266
    }
1387
1267
    if(ret != 0){
1388
 
      if (ret > 0 or errno != EINTR){
 
1268
      if (ret > 0 or errno != EINTR) {
1389
1269
        return (ret != 1) ? ret : 0;
1390
1270
      }
1391
1271
    }
1392
1272
  }
1393
1273
}
1394
1274
 
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
 
 
1686
1275
int main(int argc, char *argv[]){
1687
1276
  AvahiSServiceBrowser *sb = NULL;
1688
1277
  int error;
1694
1283
  struct ifreq network;
1695
1284
  int sd = -1;
1696
1285
  bool take_down_interface = false;
 
1286
  uid_t uid;
 
1287
  gid_t gid;
1697
1288
  char tempdir[] = "/tmp/mandosXXXXXX";
1698
1289
  bool tempdir_created = false;
1699
1290
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1766
1357
        .group = 2 },
1767
1358
      { .name = "retry", .key = 132,
1768
1359
        .arg = "SECONDS",
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",
 
1360
        .doc = "Retry interval used when denied by the mandos server",
1774
1361
        .group = 2 },
1775
1362
      /*
1776
1363
       * These reproduce what we would get without ARGP_NO_HELP
1830
1417
          argp_error(state, "Bad retry interval");
1831
1418
        }
1832
1419
        break;
1833
 
      case 133:                 /* --network-hook-dir */
1834
 
        hookdir = arg;
1835
 
        break;
1836
1420
        /*
1837
1421
         * These reproduce what we would get without ARGP_NO_HELP
1838
1422
         */
1844
1428
        argp_state_help(state, state->out_stream,
1845
1429
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1846
1430
      case 'V':                 /* --version */
1847
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1431
        fprintf(state->out_stream, "%s\n", argp_program_version);
1848
1432
        exit(argp_err_exit_status);
1849
1433
        break;
1850
1434
      default:
1877
1461
  {
1878
1462
    /* Work around Debian bug #633582:
1879
1463
       <http://bugs.debian.org/633582> */
 
1464
    struct stat st;
1880
1465
    
1881
1466
    /* Re-raise priviliges */
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;
 
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
    }
1939
1519
  }
1940
1520
  
1941
1521
  if(not debug){
1942
1522
    avahi_set_log_function(empty_log);
1943
1523
  }
1944
 
  
 
1524
 
1945
1525
  if(interface[0] == '\0'){
1946
1526
    struct dirent **direntries;
1947
 
    /* First look for interfaces that are up */
1948
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1527
    ret = scandir(sys_class_net, &direntries, good_interface,
1949
1528
                  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
 
    }
1956
1529
    if(ret >= 1){
1957
 
      /* Pick the first interface returned */
 
1530
      /* Pick the first good interface */
1958
1531
      interface = strdup(direntries[0]->d_name);
1959
1532
      if(debug){
1960
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1533
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1961
1534
      }
1962
1535
      if(interface == NULL){
1963
1536
        perror_plus("malloc");
1968
1541
      free(direntries);
1969
1542
    } else {
1970
1543
      free(direntries);
1971
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1544
      fprintf(stderr, "Could not find a network interface\n");
1972
1545
      exitcode = EXIT_FAILURE;
1973
1546
      goto end;
1974
1547
    }
1980
1553
  srand((unsigned int) time(NULL));
1981
1554
  mc.simple_poll = avahi_simple_poll_new();
1982
1555
  if(mc.simple_poll == NULL){
1983
 
    fprintf_plus(stderr,
1984
 
                 "Avahi: Failed to create simple poll object.\n");
 
1556
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1985
1557
    exitcode = EX_UNAVAILABLE;
1986
1558
    goto end;
1987
1559
  }
2050
1622
  }
2051
1623
  
2052
1624
  /* If the interface is down, bring it up */
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");
 
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
      }
2058
1766
    }
2059
1767
  }
2060
1768
  
2064
1772
  
2065
1773
  ret = init_gnutls_global(pubkey, seckey);
2066
1774
  if(ret == -1){
2067
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1775
    fprintf(stderr, "init_gnutls_global failed\n");
2068
1776
    exitcode = EX_UNAVAILABLE;
2069
1777
    goto end;
2070
1778
  } else {
2086
1794
  }
2087
1795
  
2088
1796
  if(not init_gpgme(pubkey, seckey, tempdir)){
2089
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1797
    fprintf(stderr, "init_gpgme failed\n");
2090
1798
    exitcode = EX_UNAVAILABLE;
2091
1799
    goto end;
2092
1800
  } else {
2101
1809
    /* Connect directly, do not use Zeroconf */
2102
1810
    /* (Mainly meant for debugging) */
2103
1811
    char *address = strrchr(connect_to, ':');
2104
 
    
2105
1812
    if(address == NULL){
2106
 
      fprintf_plus(stderr, "No colon in address\n");
 
1813
      fprintf(stderr, "No colon in address\n");
2107
1814
      exitcode = EX_USAGE;
2108
1815
      goto end;
2109
1816
    }
2117
1824
    tmpmax = strtoimax(address+1, &tmp, 10);
2118
1825
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2119
1826
       or tmpmax != (uint16_t)tmpmax){
2120
 
      fprintf_plus(stderr, "Bad port number\n");
 
1827
      fprintf(stderr, "Bad port number\n");
2121
1828
      exitcode = EX_USAGE;
2122
1829
      goto end;
2123
1830
    }
2153
1860
        break;
2154
1861
      }
2155
1862
      if(debug){
2156
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2157
 
                     (int)retry_interval);
 
1863
        fprintf(stderr, "Retrying in %d seconds\n",
 
1864
                (int)retry_interval);
2158
1865
      }
2159
1866
      sleep((int)retry_interval);
2160
1867
    }
2162
1869
    if (not quit_now){
2163
1870
      exitcode = EXIT_SUCCESS;
2164
1871
    }
2165
 
    
 
1872
 
2166
1873
    goto end;
2167
1874
  }
2168
1875
  
2190
1897
  
2191
1898
  /* Check if creating the Avahi server object succeeded */
2192
1899
  if(mc.server == NULL){
2193
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2194
 
                 avahi_strerror(error));
 
1900
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1901
            avahi_strerror(error));
2195
1902
    exitcode = EX_UNAVAILABLE;
2196
1903
    goto end;
2197
1904
  }
2205
1912
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2206
1913
                                   NULL, 0, browse_callback, NULL);
2207
1914
  if(sb == NULL){
2208
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2209
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1915
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1916
            avahi_strerror(avahi_server_errno(mc.server)));
2210
1917
    exitcode = EX_UNAVAILABLE;
2211
1918
    goto end;
2212
1919
  }
2218
1925
  /* Run the main loop */
2219
1926
  
2220
1927
  if(debug){
2221
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
1928
    fprintf(stderr, "Starting Avahi loop search\n");
2222
1929
  }
2223
1930
 
2224
1931
  ret = avahi_loop_with_timeout(mc.simple_poll,
2225
1932
                                (int)(retry_interval * 1000));
2226
1933
  if(debug){
2227
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2228
 
                 (ret == 0) ? "successfully" : "with error");
 
1934
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1935
            (ret == 0) ? "successfully" : "with error");
2229
1936
  }
2230
1937
  
2231
1938
 end:
2232
1939
  
2233
1940
  if(debug){
2234
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1941
    fprintf(stderr, "%s exiting\n", argv[0]);
2235
1942
  }
2236
1943
  
2237
1944
  /* Cleanup things */
2253
1960
  if(gpgme_initialized){
2254
1961
    gpgme_release(mc.ctx);
2255
1962
  }
2256
 
  
 
1963
 
2257
1964
  /* Cleans up the circular linked list of Mandos servers the client
2258
1965
     has seen */
2259
1966
  if(mc.current_server != NULL){
2265
1972
    }
2266
1973
  }
2267
1974
  
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){
 
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){
2277
1984
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2278
1985
      if(ret == -1){
2279
1986
        perror_plus("ioctl SIOCGIFFLAGS");
2280
 
      } else if(network.ifr_flags & IFF_UP){
 
1987
      } else if(network.ifr_flags & IFF_UP) {
2281
1988
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2282
1989
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2283
1990
        if(ret == -1){
2288
1995
      if(ret == -1){
2289
1996
        perror_plus("close");
2290
1997
      }
 
1998
      /* Lower privileges permanently */
 
1999
      errno = 0;
 
2000
      ret = setuid(uid);
 
2001
      if(ret == -1){
 
2002
        perror_plus("setuid");
 
2003
      }
2291
2004
    }
2292
2005
  }
2293
 
  /* Lower privileges permanently */
2294
 
  errno = 0;
2295
 
  ret = setuid(uid);
2296
 
  if(ret == -1){
2297
 
    perror_plus("setuid");
2298
 
  }
2299
2006
  
2300
2007
  /* Removes the GPGME temp directory and all files inside */
2301
2008
  if(tempdir_created){
2315
2022
        }
2316
2023
        ret = remove(fullname);
2317
2024
        if(ret == -1){
2318
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2319
 
                       strerror(errno));
 
2025
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2026
                  strerror(errno));
2320
2027
        }
2321
2028
        free(fullname);
2322
2029
      }