/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
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
89
                                   WEXITSTATUS(), WTERMSIG() */
 
90
#include <grp.h>                /* setgroups() */
90
91
 
91
92
#ifdef __linux__
92
93
#include <sys/klog.h>           /* klogctl() */
110
111
                                   init_gnutls_session(),
111
112
                                   GNUTLS_* */
112
113
#include <gnutls/openpgp.h>
113
 
                          /* gnutls_certificate_set_openpgp_key_file(),
114
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
114
                         /* gnutls_certificate_set_openpgp_key_file(),
 
115
                            GNUTLS_OPENPGP_FMT_BASE64 */
115
116
 
116
117
/* GPGME */
117
118
#include <gpgme.h>              /* All GPGME types, constants and
134
135
static const char sys_class_net[] = "/sys/class/net";
135
136
char *connect_to = NULL;
136
137
const char *hookdir = HOOKDIR;
 
138
uid_t uid = 65534;
 
139
gid_t gid = 65534;
137
140
 
138
141
/* Doubly linked list that need to be circularly linked when used */
139
142
typedef struct server{
169
172
 
170
173
/* Function to use when printing errors */
171
174
void perror_plus(const char *print_text){
 
175
  int e = errno;
172
176
  fprintf(stderr, "Mandos plugin %s: ",
173
177
          program_invocation_short_name);
 
178
  errno = e;
174
179
  perror(print_text);
175
180
}
176
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
 
177
192
/*
178
193
 * Make additional room in "buffer" for at least BUFFER_SIZE more
179
194
 * bytes. "buffer_capacity" is how much is currently allocated,
180
195
 * "buffer_length" is how much is already used.
181
196
 */
182
197
size_t incbuffer(char **buffer, size_t buffer_length,
183
 
                  size_t buffer_capacity){
 
198
                 size_t buffer_capacity){
184
199
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
185
200
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
201
    if(buffer == NULL){
192
207
}
193
208
 
194
209
/* Add server to set of servers to retry periodically */
195
 
int add_server(const char *ip, uint16_t port,
196
 
                 AvahiIfIndex if_index,
197
 
                 int af){
 
210
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
211
                int af){
198
212
  int ret;
199
213
  server *new_server = malloc(sizeof(server));
200
214
  if(new_server == NULL){
201
215
    perror_plus("malloc");
202
 
    return -1;
 
216
    return false;
203
217
  }
204
218
  *new_server = (server){ .ip = strdup(ip),
205
 
                         .port = port,
206
 
                         .if_index = if_index,
207
 
                         .af = af };
 
219
                          .port = port,
 
220
                          .if_index = if_index,
 
221
                          .af = af };
208
222
  if(new_server->ip == NULL){
209
223
    perror_plus("strdup");
210
 
    return -1;
 
224
    return false;
211
225
  }
212
226
  /* Special case of first server */
213
227
  if (mc.current_server == NULL){
224
238
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
225
239
  if(ret == -1){
226
240
    perror_plus("clock_gettime");
227
 
    return -1;
 
241
    return false;
228
242
  }
229
 
  return 0;
 
243
  return true;
230
244
}
231
245
 
232
246
/* 
233
247
 * Initialize GPGME.
234
248
 */
235
 
static bool init_gpgme(const char *seckey,
236
 
                       const char *pubkey, const char *tempdir){
 
249
static bool init_gpgme(const char *seckey, const char *pubkey,
 
250
                       const char *tempdir){
237
251
  gpgme_error_t rc;
238
252
  gpgme_engine_info_t engine_info;
239
253
  
254
268
    
255
269
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
256
270
    if(rc != GPG_ERR_NO_ERROR){
257
 
      fprintf(stderr, "Mandos plugin mandos-client: "
258
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
259
 
              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));
260
273
      return false;
261
274
    }
262
275
    
263
276
    rc = gpgme_op_import(mc.ctx, pgp_data);
264
277
    if(rc != GPG_ERR_NO_ERROR){
265
 
      fprintf(stderr, "Mandos plugin mandos-client: "
266
 
              "bad gpgme_op_import: %s: %s\n",
267
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
278
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
279
                   gpgme_strsource(rc), gpgme_strerror(rc));
268
280
      return false;
269
281
    }
270
282
    
277
289
  }
278
290
  
279
291
  if(debug){
280
 
    fprintf(stderr, "Mandos plugin mandos-client: "
281
 
            "Initializing GPGME\n");
 
292
    fprintf_plus(stderr, "Initializing GPGME\n");
282
293
  }
283
294
  
284
295
  /* Init GPGME */
285
296
  gpgme_check_version(NULL);
286
297
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
287
298
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "Mandos plugin mandos-client: "
289
 
            "bad gpgme_engine_check_version: %s: %s\n",
290
 
            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));
291
301
    return false;
292
302
  }
293
303
  
294
304
  /* Set GPGME home directory for the OpenPGP engine only */
295
305
  rc = gpgme_get_engine_info(&engine_info);
296
306
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf(stderr, "Mandos plugin mandos-client: "
298
 
            "bad gpgme_get_engine_info: %s: %s\n",
299
 
            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));
300
309
    return false;
301
310
  }
302
311
  while(engine_info != NULL){
308
317
    engine_info = engine_info->next;
309
318
  }
310
319
  if(engine_info == NULL){
311
 
    fprintf(stderr, "Mandos plugin mandos-client: "
312
 
            "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);
313
322
    return false;
314
323
  }
315
324
  
316
325
  /* Create new GPGME "context" */
317
326
  rc = gpgme_new(&(mc.ctx));
318
327
  if(rc != GPG_ERR_NO_ERROR){
319
 
    fprintf(stderr, "Mandos plugin mandos-client: "
320
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
321
 
            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));
322
331
    return false;
323
332
  }
324
333
  
343
352
  ssize_t plaintext_length = 0;
344
353
  
345
354
  if(debug){
346
 
    fprintf(stderr, "Mandos plugin mandos-client: "
347
 
            "Trying to decrypt OpenPGP data\n");
 
355
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
348
356
  }
349
357
  
350
358
  /* Create new GPGME data buffer from memory cryptotext */
351
359
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
352
360
                               0);
353
361
  if(rc != GPG_ERR_NO_ERROR){
354
 
    fprintf(stderr, "Mandos plugin mandos-client: "
355
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
356
 
            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));
357
364
    return -1;
358
365
  }
359
366
  
360
367
  /* Create new empty GPGME data buffer for the plaintext */
361
368
  rc = gpgme_data_new(&dh_plain);
362
369
  if(rc != GPG_ERR_NO_ERROR){
363
 
    fprintf(stderr, "Mandos plugin mandos-client: "
364
 
            "bad gpgme_data_new: %s: %s\n",
365
 
            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));
366
373
    gpgme_data_release(dh_crypto);
367
374
    return -1;
368
375
  }
371
378
     data buffer */
372
379
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
373
380
  if(rc != GPG_ERR_NO_ERROR){
374
 
    fprintf(stderr, "Mandos plugin mandos-client: "
375
 
            "bad gpgme_op_decrypt: %s: %s\n",
376
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
381
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
382
                 gpgme_strsource(rc), gpgme_strerror(rc));
377
383
    plaintext_length = -1;
378
384
    if(debug){
379
385
      gpgme_decrypt_result_t result;
380
386
      result = gpgme_op_decrypt_result(mc.ctx);
381
387
      if(result == NULL){
382
 
        fprintf(stderr, "Mandos plugin mandos-client: "
383
 
                "gpgme_op_decrypt_result failed\n");
 
388
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
384
389
      } else {
385
 
        fprintf(stderr, "Mandos plugin mandos-client: "
386
 
                "Unsupported algorithm: %s\n",
387
 
                result->unsupported_algorithm);
388
 
        fprintf(stderr, "Mandos plugin mandos-client: "
389
 
                "Wrong key usage: %u\n",
390
 
                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);
391
394
        if(result->file_name != NULL){
392
 
          fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                  "File name: %s\n", result->file_name);
 
395
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
394
396
        }
395
397
        gpgme_recipient_t recipient;
396
398
        recipient = result->recipients;
397
399
        while(recipient != NULL){
398
 
          fprintf(stderr, "Mandos plugin mandos-client: "
399
 
                  "Public key algorithm: %s\n",
400
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
401
 
          fprintf(stderr, "Mandos plugin mandos-client: "
402
 
                  "Key ID: %s\n", recipient->keyid);
403
 
          fprintf(stderr, "Mandos plugin mandos-client: "
404
 
                  "Secret key available: %s\n",
405
 
                  recipient->status == GPG_ERR_NO_SECKEY
406
 
                  ? "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");
407
407
          recipient = recipient->next;
408
408
        }
409
409
      }
412
412
  }
413
413
  
414
414
  if(debug){
415
 
    fprintf(stderr, "Mandos plugin mandos-client: "
416
 
            "Decryption of OpenPGP data succeeded\n");
 
415
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
417
416
  }
418
417
  
419
418
  /* Seek back to the beginning of the GPGME plaintext data buffer */
426
425
  *plaintext = NULL;
427
426
  while(true){
428
427
    plaintext_capacity = incbuffer(plaintext,
429
 
                                      (size_t)plaintext_length,
430
 
                                      plaintext_capacity);
 
428
                                   (size_t)plaintext_length,
 
429
                                   plaintext_capacity);
431
430
    if(plaintext_capacity == 0){
432
 
        perror_plus("incbuffer");
433
 
        plaintext_length = -1;
434
 
        goto decrypt_end;
 
431
      perror_plus("incbuffer");
 
432
      plaintext_length = -1;
 
433
      goto decrypt_end;
435
434
    }
436
435
    
437
436
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
450
449
  }
451
450
  
452
451
  if(debug){
453
 
    fprintf(stderr, "Mandos plugin mandos-client: "
454
 
            "Decrypted password is: ");
 
452
    fprintf_plus(stderr, "Decrypted password is: ");
455
453
    for(ssize_t i = 0; i < plaintext_length; i++){
456
454
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
457
455
    }
479
477
/* GnuTLS log function callback */
480
478
static void debuggnutls(__attribute__((unused)) int level,
481
479
                        const char* string){
482
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
480
  fprintf_plus(stderr, "GnuTLS: %s", string);
483
481
}
484
482
 
485
483
static int init_gnutls_global(const char *pubkeyfilename,
487
485
  int ret;
488
486
  
489
487
  if(debug){
490
 
    fprintf(stderr, "Mandos plugin mandos-client: "
491
 
            "Initializing GnuTLS\n");
 
488
    fprintf_plus(stderr, "Initializing GnuTLS\n");
492
489
  }
493
490
  
494
491
  ret = gnutls_global_init();
495
492
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "Mandos plugin mandos-client: "
497
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
493
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
494
                 safer_gnutls_strerror(ret));
498
495
    return -1;
499
496
  }
500
497
  
509
506
  /* OpenPGP credentials */
510
507
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
511
508
  if(ret != GNUTLS_E_SUCCESS){
512
 
    fprintf(stderr, "Mandos plugin mandos-client: "
513
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
509
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
510
                 safer_gnutls_strerror(ret));
514
511
    gnutls_global_deinit();
515
512
    return -1;
516
513
  }
517
514
  
518
515
  if(debug){
519
 
    fprintf(stderr, "Mandos plugin mandos-client: "
520
 
            "Attempting to use OpenPGP public key %s and"
521
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
522
 
            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);
523
520
  }
524
521
  
525
522
  ret = gnutls_certificate_set_openpgp_key_file
526
523
    (mc.cred, pubkeyfilename, seckeyfilename,
527
524
     GNUTLS_OPENPGP_FMT_BASE64);
528
525
  if(ret != GNUTLS_E_SUCCESS){
529
 
    fprintf(stderr,
530
 
            "Mandos plugin mandos-client: "
531
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
532
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
533
 
    fprintf(stderr, "Mandos plugin mandos-client: "
534
 
            "The GnuTLS error is: %s\n", 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));
535
531
    goto globalfail;
536
532
  }
537
533
  
538
534
  /* GnuTLS server initialization */
539
535
  ret = gnutls_dh_params_init(&mc.dh_params);
540
536
  if(ret != GNUTLS_E_SUCCESS){
541
 
    fprintf(stderr, "Mandos plugin mandos-client: "
542
 
            "Error in GnuTLS DH parameter initialization:"
543
 
            " %s\n", safer_gnutls_strerror(ret));
 
537
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
538
                 " initialization: %s\n",
 
539
                 safer_gnutls_strerror(ret));
544
540
    goto globalfail;
545
541
  }
546
542
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
547
543
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Mandos plugin mandos-client: "
549
 
            "Error in GnuTLS prime generation: %s\n",
550
 
            safer_gnutls_strerror(ret));
 
544
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
545
                 safer_gnutls_strerror(ret));
551
546
    goto globalfail;
552
547
  }
553
548
  
573
568
    }
574
569
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
575
570
  if(ret != GNUTLS_E_SUCCESS){
576
 
    fprintf(stderr, "Mandos plugin mandos-client: "
577
 
            "Error in GnuTLS session initialization: %s\n",
578
 
            safer_gnutls_strerror(ret));
 
571
    fprintf_plus(stderr,
 
572
                 "Error in GnuTLS session initialization: %s\n",
 
573
                 safer_gnutls_strerror(ret));
579
574
  }
580
575
  
581
576
  {
588
583
      }
589
584
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
590
585
    if(ret != GNUTLS_E_SUCCESS){
591
 
      fprintf(stderr, "Mandos plugin mandos-client: "
592
 
              "Syntax error at: %s\n", err);
593
 
      fprintf(stderr, "Mandos plugin mandos-client: "
594
 
              "GnuTLS error: %s\n", 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));
595
589
      gnutls_deinit(*session);
596
590
      return -1;
597
591
    }
606
600
    }
607
601
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
608
602
  if(ret != GNUTLS_E_SUCCESS){
609
 
    fprintf(stderr, "Mandos plugin mandos-client: "
610
 
            "Error setting GnuTLS credentials: %s\n",
611
 
            safer_gnutls_strerror(ret));
 
603
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
604
                 safer_gnutls_strerror(ret));
612
605
    gnutls_deinit(*session);
613
606
    return -1;
614
607
  }
659
652
    pf = PF_INET;
660
653
    break;
661
654
  default:
662
 
    fprintf(stderr, "Mandos plugin mandos-client: "
663
 
            "Bad address family: %d\n", af);
 
655
    fprintf_plus(stderr, "Bad address family: %d\n", af);
664
656
    errno = EINVAL;
665
657
    return -1;
666
658
  }
671
663
  }
672
664
  
673
665
  if(debug){
674
 
    fprintf(stderr, "Mandos plugin mandos-client: "
675
 
            "Setting up a TCP connection to %s, port %" PRIu16
676
 
            "\n", ip, port);
 
666
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
667
                 PRIu16 "\n", ip, port);
677
668
  }
678
669
  
679
670
  tcp_sd = socket(pf, SOCK_STREAM, 0);
705
696
  }
706
697
  if(ret == 0){
707
698
    int e = errno;
708
 
    fprintf(stderr, "Mandos plugin mandos-client: "
709
 
            "Bad address: %s\n", ip);
 
699
    fprintf_plus(stderr, "Bad address: %s\n", ip);
710
700
    errno = e;
711
701
    goto mandos_end;
712
702
  }
717
707
    
718
708
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
719
709
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
720
 
                              -Wunreachable-code*/
 
710
                                -Wunreachable-code*/
721
711
      if(if_index == AVAHI_IF_UNSPEC){
722
 
        fprintf(stderr, "Mandos plugin mandos-client: "
723
 
                "An IPv6 link-local address is incomplete"
724
 
                " without a network interface\n");
 
712
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
713
                     " incomplete without a network interface\n");
725
714
        errno = EINVAL;
726
715
        goto mandos_end;
727
716
      }
745
734
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
746
735
        perror_plus("if_indextoname");
747
736
      } else {
748
 
        fprintf(stderr, "Mandos plugin mandos-client: "
749
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
750
 
                ip, interface, port);
 
737
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
738
                     "\n", ip, interface, port);
751
739
      }
752
740
    } else {
753
 
      fprintf(stderr, "Mandos plugin mandos-client: "
754
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
741
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
742
                   ip, port);
755
743
    }
756
744
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
757
745
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
767
755
      perror_plus("inet_ntop");
768
756
    } else {
769
757
      if(strcmp(addrstr, ip) != 0){
770
 
        fprintf(stderr, "Mandos plugin mandos-client: "
771
 
                "Canonical address form: %s\n", addrstr);
 
758
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
772
759
      }
773
760
    }
774
761
  }
802
789
  while(true){
803
790
    size_t out_size = strlen(out);
804
791
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
805
 
                                   out_size - written));
 
792
                                        out_size - written));
806
793
    if(ret == -1){
807
794
      int e = errno;
808
795
      perror_plus("write");
828
815
  }
829
816
  
830
817
  if(debug){
831
 
    fprintf(stderr, "Mandos plugin mandos-client: "
832
 
            "Establishing TLS session with %s\n", ip);
 
818
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
833
819
  }
834
820
  
835
821
  if(quit_now){
837
823
    goto mandos_end;
838
824
  }
839
825
  
840
 
  /* Spurious warning from -Wint-to-pointer-cast */
841
 
  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);
842
831
  
843
832
  if(quit_now){
844
833
    errno = EINTR;
855
844
  
856
845
  if(ret != GNUTLS_E_SUCCESS){
857
846
    if(debug){
858
 
      fprintf(stderr, "Mandos plugin mandos-client: "
859
 
              "*** GnuTLS Handshake failed ***\n");
 
847
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
860
848
      gnutls_perror(ret);
861
849
    }
862
850
    errno = EPROTO;
866
854
  /* Read OpenPGP packet that contains the wanted password */
867
855
  
868
856
  if(debug){
869
 
    fprintf(stderr, "Mandos plugin mandos-client: "
870
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
857
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
858
                 " %s\n", ip);
871
859
  }
872
860
  
873
861
  while(true){
878
866
    }
879
867
    
880
868
    buffer_capacity = incbuffer(&buffer, buffer_length,
881
 
                                   buffer_capacity);
 
869
                                buffer_capacity);
882
870
    if(buffer_capacity == 0){
883
871
      int e = errno;
884
872
      perror_plus("incbuffer");
911
899
          }
912
900
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
913
901
        if(ret < 0){
914
 
          fprintf(stderr, "Mandos plugin mandos-client: "
915
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
902
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
903
                       "***\n");
916
904
          gnutls_perror(ret);
917
905
          errno = EPROTO;
918
906
          goto mandos_end;
919
907
        }
920
908
        break;
921
909
      default:
922
 
        fprintf(stderr, "Mandos plugin mandos-client: "
923
 
                "Unknown error while reading data from"
924
 
                " encrypted session with Mandos server\n");
 
910
        fprintf_plus(stderr, "Unknown error while reading data from"
 
911
                     " encrypted session with Mandos server\n");
925
912
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
926
913
        errno = EIO;
927
914
        goto mandos_end;
932
919
  }
933
920
  
934
921
  if(debug){
935
 
    fprintf(stderr, "Mandos plugin mandos-client: "
936
 
            "Closing TLS session\n");
 
922
    fprintf_plus(stderr, "Closing TLS session\n");
937
923
  }
938
924
  
939
925
  if(quit_now){
951
937
  
952
938
  if(buffer_length > 0){
953
939
    ssize_t decrypted_buffer_size;
954
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
955
 
                                               buffer_length,
 
940
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
956
941
                                               &decrypted_buffer);
957
942
    if(decrypted_buffer_size >= 0){
958
943
      
969
954
        if(ret == 0 and ferror(stdout)){
970
955
          int e = errno;
971
956
          if(debug){
972
 
            fprintf(stderr, "Mandos plugin mandos-client: "
973
 
                    "Error writing encrypted data: %s\n",
974
 
                    strerror(errno));
 
957
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
958
                         strerror(errno));
975
959
          }
976
960
          errno = e;
977
961
          goto mandos_end;
1034
1018
  switch(event){
1035
1019
  default:
1036
1020
  case AVAHI_RESOLVER_FAILURE:
1037
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1038
 
            "(Avahi Resolver) Failed to resolve service '%s'"
1039
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1040
 
            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)));
1041
1025
    break;
1042
1026
    
1043
1027
  case AVAHI_RESOLVER_FOUND:
1045
1029
      char ip[AVAHI_ADDRESS_STR_MAX];
1046
1030
      avahi_address_snprint(ip, sizeof(ip), address);
1047
1031
      if(debug){
1048
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1049
 
                "Mandos server \"%s\" found on %s (%s, %"
1050
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1051
 
                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);
1052
1035
      }
1053
1036
      int ret = start_mandos_communication(ip, port, interface,
1054
1037
                                           avahi_proto_to_af(proto));
1055
1038
      if(ret == 0){
1056
1039
        avahi_simple_poll_quit(mc.simple_poll);
1057
1040
      } else {
1058
 
        ret = add_server(ip, port, interface,
1059
 
                         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
        }
1060
1046
      }
1061
1047
    }
1062
1048
  }
1086
1072
  default:
1087
1073
  case AVAHI_BROWSER_FAILURE:
1088
1074
    
1089
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1090
 
            "(Avahi browser) %s\n",
1091
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1075
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1076
                 avahi_strerror(avahi_server_errno(mc.server)));
1092
1077
    avahi_simple_poll_quit(mc.simple_poll);
1093
1078
    return;
1094
1079
    
1101
1086
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1102
1087
                                    name, type, domain, protocol, 0,
1103
1088
                                    resolve_callback, NULL) == NULL)
1104
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1105
 
              "Avahi: Failed to resolve service '%s': %s\n",
1106
 
              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)));
1107
1092
    break;
1108
1093
    
1109
1094
  case AVAHI_BROWSER_REMOVE:
1112
1097
  case AVAHI_BROWSER_ALL_FOR_NOW:
1113
1098
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1114
1099
    if(debug){
1115
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1116
 
              "No Mandos server found, still searching...\n");
 
1100
      fprintf_plus(stderr, "No Mandos server found, still"
 
1101
                   " searching...\n");
1117
1102
    }
1118
1103
    break;
1119
1104
  }
1158
1143
  /* Reject the loopback device */
1159
1144
  if(ifr->ifr_flags & IFF_LOOPBACK){
1160
1145
    if(debug){
1161
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1162
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1146
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1147
                   ifname);
1163
1148
    }
1164
1149
    return false;
1165
1150
  }
1166
1151
  /* Accept point-to-point devices only if connect_to is specified */
1167
1152
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1168
1153
    if(debug){
1169
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1170
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1154
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1155
                   " \"%s\"\n", ifname);
1171
1156
    }
1172
1157
    return true;
1173
1158
  }
1174
1159
  /* Otherwise, reject non-broadcast-capable devices */
1175
1160
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1176
1161
    if(debug){
1177
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1178
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1162
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1163
                   " \"%s\"\n", ifname);
1179
1164
    }
1180
1165
    return false;
1181
1166
  }
1182
1167
  /* Reject non-ARP interfaces (including dummy interfaces) */
1183
1168
  if(ifr->ifr_flags & IFF_NOARP){
1184
1169
    if(debug){
1185
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1186
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1170
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1171
                   ifname);
1187
1172
    }
1188
1173
    return false;
1189
1174
  }
1190
1175
  
1191
1176
  /* Accept this device */
1192
1177
  if(debug){
1193
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1194
 
            "Interface \"%s\" is good\n", ifname);
 
1178
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1195
1179
  }
1196
1180
  return true;
1197
1181
}
1209
1193
  struct ifreq ifr;
1210
1194
  if(not get_flags(if_entry->d_name, &ifr)){
1211
1195
    if(debug){
1212
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1213
 
              "Failed to get flags for interface \"%s\"\n",
1214
 
              if_entry->d_name);
 
1196
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1197
                   "\"%s\"\n", if_entry->d_name);
1215
1198
    }
1216
1199
    return 0;
1217
1200
  }
1235
1218
  struct ifreq ifr;
1236
1219
  if(not get_flags(if_entry->d_name, &ifr)){
1237
1220
    if(debug){
1238
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1239
 
              "Failed to get flags for interface \"%s\"\n",
1240
 
              if_entry->d_name);
 
1221
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1222
                   "\"%s\"\n", if_entry->d_name);
1241
1223
    }
1242
1224
    return 0;
1243
1225
  }
1245
1227
  /* Reject down interfaces */
1246
1228
  if(not (ifr.ifr_flags & IFF_UP)){
1247
1229
    if(debug){
1248
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1249
 
              "Rejecting down interface \"%s\"\n",
1250
 
              if_entry->d_name);
 
1230
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1231
                   if_entry->d_name);
1251
1232
    }
1252
1233
    return 0;
1253
1234
  }
1255
1236
  /* Reject non-running interfaces */
1256
1237
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1257
1238
    if(debug){
1258
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1259
 
              "Rejecting non-running interface \"%s\"\n",
1260
 
              if_entry->d_name);
 
1239
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1240
                   if_entry->d_name);
1261
1241
    }
1262
1242
    return 0;
1263
1243
  }
1282
1262
/* Is this directory entry a runnable program? */
1283
1263
int runnable_hook(const struct dirent *direntry){
1284
1264
  int ret;
 
1265
  size_t sret;
1285
1266
  struct stat st;
1286
1267
  
1287
1268
  if((direntry->d_name)[0] == '\0'){
1289
1270
    return 0;
1290
1271
  }
1291
1272
  
1292
 
  /* Save pointer to last character */
1293
 
  char *end = strchr(direntry->d_name, '\0')-1;
1294
 
  
1295
 
  if(*end == '~'){
1296
 
    /* Backup name~ */
1297
 
    return 0;
1298
 
  }
1299
 
  
1300
 
  if(((direntry->d_name)[0] == '#')
1301
 
     and (*end == '#')){
1302
 
    /* Temporary #name# */
1303
 
    return 0;
1304
 
  }
1305
 
  
1306
 
  /* XXX more rules here */
 
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
  }
1307
1285
  
1308
1286
  char *fullname = NULL;
1309
 
  ret = asprintf(&fullname, "%s/%s", hookdir,
1310
 
                 direntry->d_name);
 
1287
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1311
1288
  if(ret < 0){
1312
1289
    perror_plus("asprintf");
1313
1290
    return 0;
1316
1293
  ret = stat(fullname, &st);
1317
1294
  if(ret == -1){
1318
1295
    if(debug){
1319
 
      perror_plus("Could not stat plugin");
 
1296
      perror_plus("Could not stat hook");
1320
1297
    }
1321
1298
    return 0;
1322
1299
  }
1323
1300
  if(not (S_ISREG(st.st_mode))){
1324
1301
    /* Not a regular file */
 
1302
    if(debug){
 
1303
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1304
                   direntry->d_name);
 
1305
    }
1325
1306
    return 0;
1326
1307
  }
1327
1308
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1328
1309
    /* Not executable */
 
1310
    if(debug){
 
1311
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1312
                   direntry->d_name);
 
1313
    }
1329
1314
    return 0;
1330
1315
  }
 
1316
  if(debug){
 
1317
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1318
                 direntry->d_name);
 
1319
  }
1331
1320
  return 1;
1332
1321
}
1333
1322
 
1340
1329
  while(true){
1341
1330
    if(mc.current_server == NULL){
1342
1331
      if (debug){
1343
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1344
 
                "Wait until first server is found. No timeout!\n");
 
1332
        fprintf_plus(stderr, "Wait until first server is found."
 
1333
                     " No timeout!\n");
1345
1334
      }
1346
1335
      ret = avahi_simple_poll_iterate(s, -1);
1347
1336
    } else {
1348
1337
      if (debug){
1349
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1350
 
                "Check current_server if we should run it,"
1351
 
                " or wait\n");
 
1338
        fprintf_plus(stderr, "Check current_server if we should run"
 
1339
                     " it, or wait\n");
1352
1340
      }
1353
1341
      /* the current time */
1354
1342
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1370
1358
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1371
1359
      
1372
1360
      if (debug){
1373
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1374
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1361
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1362
                     block_time);
1375
1363
      }
1376
1364
      
1377
1365
      if(block_time <= 0){
1404
1392
  }
1405
1393
}
1406
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
 
1407
1684
int main(int argc, char *argv[]){
1408
1685
  AvahiSServiceBrowser *sb = NULL;
1409
1686
  int error;
1415
1692
  struct ifreq network;
1416
1693
  int sd = -1;
1417
1694
  bool take_down_interface = false;
1418
 
  uid_t uid;
1419
 
  gid_t gid;
1420
1695
  char tempdir[] = "/tmp/mandosXXXXXX";
1421
1696
  bool tempdir_created = false;
1422
1697
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1489
1764
        .group = 2 },
1490
1765
      { .name = "retry", .key = 132,
1491
1766
        .arg = "SECONDS",
1492
 
        .doc = "Retry interval used when denied by the mandos server",
 
1767
        .doc = "Retry interval used when denied by the Mandos server",
1493
1768
        .group = 2 },
1494
1769
      { .name = "network-hook-dir", .key = 133,
1495
1770
        .arg = "DIR",
1567
1842
        argp_state_help(state, state->out_stream,
1568
1843
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1569
1844
      case 'V':                 /* --version */
1570
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1571
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1845
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1572
1846
        exit(argp_err_exit_status);
1573
1847
        break;
1574
1848
      default:
1601
1875
  {
1602
1876
    /* Work around Debian bug #633582:
1603
1877
       <http://bugs.debian.org/633582> */
1604
 
    struct stat st;
1605
1878
    
1606
1879
    /* Re-raise priviliges */
1607
 
    errno = 0;
1608
 
    ret = seteuid(0);
1609
 
    if(ret == -1){
1610
 
      perror_plus("seteuid");
1611
 
    }
1612
 
    
1613
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1614
 
      int seckey_fd = open(seckey, O_RDONLY);
1615
 
      if(seckey_fd == -1){
1616
 
        perror_plus("open");
1617
 
      } else {
1618
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1619
 
        if(ret == -1){
1620
 
          perror_plus("fstat");
1621
 
        } else {
1622
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1623
 
            ret = fchown(seckey_fd, uid, gid);
1624
 
            if(ret == -1){
1625
 
              perror_plus("fchown");
1626
 
            }
1627
 
          }
1628
 
        }
1629
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1630
 
      }
1631
 
    }
1632
 
    
1633
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1634
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1635
 
      if(pubkey_fd == -1){
1636
 
        perror_plus("open");
1637
 
      } else {
1638
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1639
 
        if(ret == -1){
1640
 
          perror_plus("fstat");
1641
 
        } else {
1642
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1643
 
            ret = fchown(pubkey_fd, uid, gid);
1644
 
            if(ret == -1){
1645
 
              perror_plus("fchown");
1646
 
            }
1647
 
          }
1648
 
        }
1649
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1650
 
      }
1651
 
    }
1652
 
    
1653
 
    /* Lower privileges */
1654
 
    errno = 0;
1655
 
    ret = seteuid(uid);
1656
 
    if(ret == -1){
1657
 
      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
      }
1658
1931
    }
1659
1932
  }
1660
1933
  
1661
 
  /* Find network hooks and run them */
1662
 
  {
1663
 
    struct dirent **direntries;
1664
 
    struct dirent *direntry;
1665
 
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
1666
 
                           alphasort);
1667
 
    if(numhooks == -1){
1668
 
      perror_plus("scandir");
1669
 
    } else {
1670
 
      int devnull = open("/dev/null", O_RDONLY);
1671
 
      for(int i = 0; i < numhooks; i++){
1672
 
        direntry = direntries[0];
1673
 
        char *fullname = NULL;
1674
 
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1675
 
        if(ret < 0){
1676
 
          perror_plus("asprintf");
1677
 
          continue;
1678
 
        }
1679
 
        pid_t hook_pid = fork();
1680
 
        if(hook_pid == 0){
1681
 
          /* Child */
1682
 
          dup2(devnull, STDIN_FILENO);
1683
 
          close(devnull);
1684
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1685
 
          ret = setenv("DEVICE", interface, 1);
1686
 
          if(ret == -1){
1687
 
            perror_plus("setenv");
1688
 
            exit(1);
1689
 
          }
1690
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1691
 
          if(ret == -1){
1692
 
            perror_plus("setenv");
1693
 
            exit(1);
1694
 
          }
1695
 
          ret = setenv("MODE", "start", 1);
1696
 
          if(ret == -1){
1697
 
            perror_plus("setenv");
1698
 
            exit(1);
1699
 
          }
1700
 
          char *delaystring;
1701
 
          ret = asprintf(&delaystring, "%f", delay);
1702
 
          if(ret == -1){
1703
 
            perror_plus("asprintf");
1704
 
            exit(1);
1705
 
          }
1706
 
          ret = setenv("DELAY", delaystring, 1);
1707
 
          if(ret == -1){
1708
 
            free(delaystring);
1709
 
            perror_plus("setenv");
1710
 
            exit(1);
1711
 
          }
1712
 
          free(delaystring);
1713
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1714
 
          perror_plus("execl");
1715
 
        } else {
1716
 
          int status;
1717
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1718
 
            perror_plus("waitpid");
1719
 
            free(fullname);
1720
 
            continue;
1721
 
          }
1722
 
          if(WIFEXITED(status)){
1723
 
            if(WEXITSTATUS(status) != 0){
1724
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1725
 
                      "Warning: network hook \"%s\" exited"
1726
 
                      " with status %d\n", direntry->d_name,
1727
 
                      WEXITSTATUS(status));
1728
 
              free(fullname);
1729
 
              continue;
1730
 
            }
1731
 
          } else if(WIFSIGNALED(status)){
1732
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1733
 
                    "Warning: network hook \"%s\" died by"
1734
 
                    " signal %d\n", direntry->d_name,
1735
 
                    WTERMSIG(status));
1736
 
            free(fullname);
1737
 
            continue;
1738
 
          } else {
1739
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1740
 
                    "Warning: network hook \"%s\" crashed\n",
1741
 
                    direntry->d_name);
1742
 
            free(fullname);
1743
 
            continue;
1744
 
          }
1745
 
        }
1746
 
        free(fullname);
1747
 
        if(quit_now){
1748
 
          goto end;
1749
 
        }
1750
 
      }
1751
 
      close(devnull);
1752
 
    }
 
1934
  /* Run network hooks */
 
1935
  if(not run_network_hooks("start", interface, delay)){
 
1936
    goto end;
1753
1937
  }
1754
1938
  
1755
1939
  if(not debug){
1771
1955
      /* Pick the first interface returned */
1772
1956
      interface = strdup(direntries[0]->d_name);
1773
1957
      if(debug){
1774
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1775
 
                "Using interface \"%s\"\n", interface);
 
1958
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1776
1959
      }
1777
1960
      if(interface == NULL){
1778
1961
        perror_plus("malloc");
1783
1966
      free(direntries);
1784
1967
    } else {
1785
1968
      free(direntries);
1786
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1787
 
              "Could not find a network interface\n");
 
1969
      fprintf_plus(stderr, "Could not find a network interface\n");
1788
1970
      exitcode = EXIT_FAILURE;
1789
1971
      goto end;
1790
1972
    }
1796
1978
  srand((unsigned int) time(NULL));
1797
1979
  mc.simple_poll = avahi_simple_poll_new();
1798
1980
  if(mc.simple_poll == NULL){
1799
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1800
 
            "Avahi: Failed to create simple poll object.\n");
 
1981
    fprintf_plus(stderr,
 
1982
                 "Avahi: Failed to create simple poll object.\n");
1801
1983
    exitcode = EX_UNAVAILABLE;
1802
1984
    goto end;
1803
1985
  }
1866
2048
  }
1867
2049
  
1868
2050
  /* If the interface is down, bring it up */
1869
 
  if(strcmp(interface, "none") != 0){
1870
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1871
 
    if(if_index == 0){
1872
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1873
 
              "No such interface: \"%s\"\n", interface);
1874
 
      exitcode = EX_UNAVAILABLE;
1875
 
      goto end;
1876
 
    }
1877
 
    
1878
 
    if(quit_now){
1879
 
      goto end;
1880
 
    }
1881
 
    
1882
 
    /* Re-raise priviliges */
1883
 
    errno = 0;
1884
 
    ret = seteuid(0);
1885
 
    if(ret == -1){
1886
 
      perror_plus("seteuid");
1887
 
    }
1888
 
    
1889
 
#ifdef __linux__
1890
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1891
 
       messages about the network interface to mess up the prompt */
1892
 
    ret = klogctl(8, NULL, 5);
1893
 
    bool restore_loglevel = true;
1894
 
    if(ret == -1){
1895
 
      restore_loglevel = false;
1896
 
      perror_plus("klogctl");
1897
 
    }
1898
 
#endif  /* __linux__ */
1899
 
    
1900
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1901
 
    if(sd < 0){
1902
 
      perror_plus("socket");
1903
 
      exitcode = EX_OSERR;
1904
 
#ifdef __linux__
1905
 
      if(restore_loglevel){
1906
 
        ret = klogctl(7, NULL, 0);
1907
 
        if(ret == -1){
1908
 
          perror_plus("klogctl");
1909
 
        }
1910
 
      }
1911
 
#endif  /* __linux__ */
1912
 
      /* Lower privileges */
1913
 
      errno = 0;
1914
 
      ret = seteuid(uid);
1915
 
      if(ret == -1){
1916
 
        perror_plus("seteuid");
1917
 
      }
1918
 
      goto end;
1919
 
    }
1920
 
    strcpy(network.ifr_name, interface);
1921
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1922
 
    if(ret == -1){
1923
 
      perror_plus("ioctl SIOCGIFFLAGS");
1924
 
#ifdef __linux__
1925
 
      if(restore_loglevel){
1926
 
        ret = klogctl(7, NULL, 0);
1927
 
        if(ret == -1){
1928
 
          perror_plus("klogctl");
1929
 
        }
1930
 
      }
1931
 
#endif  /* __linux__ */
1932
 
      exitcode = EX_OSERR;
1933
 
      /* Lower privileges */
1934
 
      errno = 0;
1935
 
      ret = seteuid(uid);
1936
 
      if(ret == -1){
1937
 
        perror_plus("seteuid");
1938
 
      }
1939
 
      goto end;
1940
 
    }
1941
 
    if((network.ifr_flags & IFF_UP) == 0){
1942
 
      network.ifr_flags |= IFF_UP;
1943
 
      take_down_interface = true;
1944
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1945
 
      if(ret == -1){
1946
 
        take_down_interface = false;
1947
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1948
 
        exitcode = EX_OSERR;
1949
 
#ifdef __linux__
1950
 
        if(restore_loglevel){
1951
 
          ret = klogctl(7, NULL, 0);
1952
 
          if(ret == -1){
1953
 
            perror_plus("klogctl");
1954
 
          }
1955
 
        }
1956
 
#endif  /* __linux__ */
1957
 
        /* Lower privileges */
1958
 
        errno = 0;
1959
 
        ret = seteuid(uid);
1960
 
        if(ret == -1){
1961
 
          perror_plus("seteuid");
1962
 
        }
1963
 
        goto end;
1964
 
      }
1965
 
    }
1966
 
    /* Sleep checking until interface is running.
1967
 
       Check every 0.25s, up to total time of delay */
1968
 
    for(int i=0; i < delay * 4; i++){
1969
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1970
 
      if(ret == -1){
1971
 
        perror_plus("ioctl SIOCGIFFLAGS");
1972
 
      } else if(network.ifr_flags & IFF_RUNNING){
1973
 
        break;
1974
 
      }
1975
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1976
 
      ret = nanosleep(&sleeptime, NULL);
1977
 
      if(ret == -1 and errno != EINTR){
1978
 
        perror_plus("nanosleep");
1979
 
      }
1980
 
    }
1981
 
    if(not take_down_interface){
1982
 
      /* We won't need the socket anymore */
1983
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1984
 
      if(ret == -1){
1985
 
        perror_plus("close");
1986
 
      }
1987
 
    }
1988
 
#ifdef __linux__
1989
 
    if(restore_loglevel){
1990
 
      /* Restores kernel loglevel to default */
1991
 
      ret = klogctl(7, NULL, 0);
1992
 
      if(ret == -1){
1993
 
        perror_plus("klogctl");
1994
 
      }
1995
 
    }
1996
 
#endif  /* __linux__ */
1997
 
    /* Lower privileges */
1998
 
    errno = 0;
1999
 
    if(take_down_interface){
2000
 
      /* Lower privileges */
2001
 
      ret = seteuid(uid);
2002
 
      if(ret == -1){
2003
 
        perror_plus("seteuid");
2004
 
      }
2005
 
    } else {
2006
 
      /* Lower privileges permanently */
2007
 
      ret = setuid(uid);
2008
 
      if(ret == -1){
2009
 
        perror_plus("setuid");
2010
 
      }
 
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");
2011
2056
    }
2012
2057
  }
2013
2058
  
2017
2062
  
2018
2063
  ret = init_gnutls_global(pubkey, seckey);
2019
2064
  if(ret == -1){
2020
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2021
 
            "init_gnutls_global failed\n");
 
2065
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2022
2066
    exitcode = EX_UNAVAILABLE;
2023
2067
    goto end;
2024
2068
  } else {
2040
2084
  }
2041
2085
  
2042
2086
  if(not init_gpgme(pubkey, seckey, tempdir)){
2043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2044
 
            "init_gpgme failed\n");
 
2087
    fprintf_plus(stderr, "init_gpgme failed\n");
2045
2088
    exitcode = EX_UNAVAILABLE;
2046
2089
    goto end;
2047
2090
  } else {
2056
2099
    /* Connect directly, do not use Zeroconf */
2057
2100
    /* (Mainly meant for debugging) */
2058
2101
    char *address = strrchr(connect_to, ':');
 
2102
    
2059
2103
    if(address == NULL){
2060
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2061
 
              "No colon in address\n");
 
2104
      fprintf_plus(stderr, "No colon in address\n");
2062
2105
      exitcode = EX_USAGE;
2063
2106
      goto end;
2064
2107
    }
2072
2115
    tmpmax = strtoimax(address+1, &tmp, 10);
2073
2116
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2074
2117
       or tmpmax != (uint16_t)tmpmax){
2075
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2076
 
              "Bad port number\n");
 
2118
      fprintf_plus(stderr, "Bad port number\n");
2077
2119
      exitcode = EX_USAGE;
2078
2120
      goto end;
2079
2121
    }
2109
2151
        break;
2110
2152
      }
2111
2153
      if(debug){
2112
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2113
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2154
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2155
                     (int)retry_interval);
2114
2156
      }
2115
2157
      sleep((int)retry_interval);
2116
2158
    }
2146
2188
  
2147
2189
  /* Check if creating the Avahi server object succeeded */
2148
2190
  if(mc.server == NULL){
2149
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2150
 
            "Failed to create Avahi server: %s\n",
2151
 
            avahi_strerror(error));
 
2191
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2192
                 avahi_strerror(error));
2152
2193
    exitcode = EX_UNAVAILABLE;
2153
2194
    goto end;
2154
2195
  }
2162
2203
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2163
2204
                                   NULL, 0, browse_callback, NULL);
2164
2205
  if(sb == NULL){
2165
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2166
 
            "Failed to create service browser: %s\n",
2167
 
            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)));
2168
2208
    exitcode = EX_UNAVAILABLE;
2169
2209
    goto end;
2170
2210
  }
2176
2216
  /* Run the main loop */
2177
2217
  
2178
2218
  if(debug){
2179
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2180
 
            "Starting Avahi loop search\n");
 
2219
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2181
2220
  }
2182
2221
 
2183
2222
  ret = avahi_loop_with_timeout(mc.simple_poll,
2184
2223
                                (int)(retry_interval * 1000));
2185
2224
  if(debug){
2186
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2187
 
            "avahi_loop_with_timeout exited %s\n",
2188
 
            (ret == 0) ? "successfully" : "with error");
 
2225
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2226
                 (ret == 0) ? "successfully" : "with error");
2189
2227
  }
2190
2228
  
2191
2229
 end:
2192
2230
  
2193
2231
  if(debug){
2194
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2195
 
            "%s exiting\n", argv[0]);
 
2232
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2196
2233
  }
2197
2234
  
2198
2235
  /* Cleanup things */
2214
2251
  if(gpgme_initialized){
2215
2252
    gpgme_release(mc.ctx);
2216
2253
  }
2217
 
 
 
2254
  
2218
2255
  /* Cleans up the circular linked list of Mandos servers the client
2219
2256
     has seen */
2220
2257
  if(mc.current_server != NULL){
2226
2263
    }
2227
2264
  }
2228
2265
  
2229
 
  /* XXX run network hooks "stop" here  */
 
2266
  /* Run network hooks */
 
2267
  run_network_hooks("stop", interface, delay);
2230
2268
  
2231
 
  /* Take down the network interface */
2232
 
  if(take_down_interface){
2233
 
    /* Re-raise priviliges */
2234
 
    errno = 0;
2235
 
    ret = seteuid(0);
2236
 
    if(ret == -1){
2237
 
      perror_plus("seteuid");
2238
 
    }
2239
 
    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){
2240
2275
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2241
2276
      if(ret == -1){
2242
2277
        perror_plus("ioctl SIOCGIFFLAGS");
2251
2286
      if(ret == -1){
2252
2287
        perror_plus("close");
2253
2288
      }
2254
 
      /* Lower privileges permanently */
2255
 
      errno = 0;
2256
 
      ret = setuid(uid);
2257
 
      if(ret == -1){
2258
 
        perror_plus("setuid");
2259
 
      }
2260
2289
    }
2261
2290
  }
 
2291
  /* Lower privileges permanently */
 
2292
  errno = 0;
 
2293
  ret = setuid(uid);
 
2294
  if(ret == -1){
 
2295
    perror_plus("setuid");
 
2296
  }
2262
2297
  
2263
2298
  /* Removes the GPGME temp directory and all files inside */
2264
2299
  if(tempdir_created){
2278
2313
        }
2279
2314
        ret = remove(fullname);
2280
2315
        if(ret == -1){
2281
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2282
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2316
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2317
                       strerror(errno));
2283
2318
        }
2284
2319
        free(fullname);
2285
2320
      }