/mandos/trunk

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

« back to all changes in this revision

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

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

Show diffs side-by-side

added added

removed removed

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