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