/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-13 22:06:57 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120613220657-qvq7c7nrndl3t413
* plugins.d/mandos-client.c (get_flags): Don't clobber errno.
  (up_interface): Removed; replaced with "interface_is_up".
  (interface_is_up, interface_is_running,
   lower_privileges_permanently, take_down_interface): New.
  (bring_up_interface): Return "error_t".  Use new functions
                        "interface_is_up", "get_flags", and
                        "interface_is_running".
  (main): Save all interfaces either autodetected or specified with
          --interface in argz vector "interfaces".  Save interfaces to
          take down on exit in argz vector "interfaces_to_take_down".
          Save interface names for DEVICE variable to network hooks as
          argz_vector "interfaces_hooks".  Bug fix: Be privileged
          while stopping network hooks.
* plugins.d/mandos-client.xml (SYNOPSIS): Changed --interface synopsis.
  (DESCRIPTION): Updated to document use of all interfaces.
  (OPTIONS): Updated description of "--interface".
* network-hooks.d/bridge: Parse comma-separated DEVICE environment
                          variable.
* network-hooks.d/openvpn: - '' -
* network-hooks.d/wireless: - '' -

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() */
 
91
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
92
                                   argz_delete(), argz_append(),
 
93
                                   argz_stringify(), argz_add(),
 
94
                                   argz_count() */
90
95
 
91
96
#ifdef __linux__
92
97
#include <sys/klog.h>           /* klogctl() */
110
115
                                   init_gnutls_session(),
111
116
                                   GNUTLS_* */
112
117
#include <gnutls/openpgp.h>
113
 
                          /* gnutls_certificate_set_openpgp_key_file(),
114
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
118
                         /* gnutls_certificate_set_openpgp_key_file(),
 
119
                            GNUTLS_OPENPGP_FMT_BASE64 */
115
120
 
116
121
/* GPGME */
117
122
#include <gpgme.h>              /* All GPGME types, constants and
134
139
static const char sys_class_net[] = "/sys/class/net";
135
140
char *connect_to = NULL;
136
141
const char *hookdir = HOOKDIR;
 
142
uid_t uid = 65534;
 
143
gid_t gid = 65534;
137
144
 
138
145
/* Doubly linked list that need to be circularly linked when used */
139
146
typedef struct server{
169
176
 
170
177
/* Function to use when printing errors */
171
178
void perror_plus(const char *print_text){
 
179
  int e = errno;
172
180
  fprintf(stderr, "Mandos plugin %s: ",
173
181
          program_invocation_short_name);
 
182
  errno = e;
174
183
  perror(print_text);
175
184
}
176
185
 
 
186
__attribute__((format (gnu_printf, 2, 3)))
 
187
int fprintf_plus(FILE *stream, const char *format, ...){
 
188
  va_list ap;
 
189
  va_start (ap, format);
 
190
  
 
191
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
192
                             program_invocation_short_name));
 
193
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
194
}
 
195
 
177
196
/*
178
197
 * Make additional room in "buffer" for at least BUFFER_SIZE more
179
198
 * bytes. "buffer_capacity" is how much is currently allocated,
180
199
 * "buffer_length" is how much is already used.
181
200
 */
182
201
size_t incbuffer(char **buffer, size_t buffer_length,
183
 
                  size_t buffer_capacity){
 
202
                 size_t buffer_capacity){
184
203
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
185
204
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
205
    if(buffer == NULL){
192
211
}
193
212
 
194
213
/* 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){
 
214
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
215
                int af){
198
216
  int ret;
199
217
  server *new_server = malloc(sizeof(server));
200
218
  if(new_server == NULL){
201
219
    perror_plus("malloc");
202
 
    return -1;
 
220
    return false;
203
221
  }
204
222
  *new_server = (server){ .ip = strdup(ip),
205
 
                         .port = port,
206
 
                         .if_index = if_index,
207
 
                         .af = af };
 
223
                          .port = port,
 
224
                          .if_index = if_index,
 
225
                          .af = af };
208
226
  if(new_server->ip == NULL){
209
227
    perror_plus("strdup");
210
 
    return -1;
 
228
    return false;
211
229
  }
212
230
  /* Special case of first server */
213
231
  if (mc.current_server == NULL){
224
242
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
225
243
  if(ret == -1){
226
244
    perror_plus("clock_gettime");
227
 
    return -1;
 
245
    return false;
228
246
  }
229
 
  return 0;
 
247
  return true;
230
248
}
231
249
 
232
250
/* 
233
251
 * Initialize GPGME.
234
252
 */
235
 
static bool init_gpgme(const char *seckey,
236
 
                       const char *pubkey, const char *tempdir){
 
253
static bool init_gpgme(const char *seckey, const char *pubkey,
 
254
                       const char *tempdir){
237
255
  gpgme_error_t rc;
238
256
  gpgme_engine_info_t engine_info;
239
257
  
254
272
    
255
273
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
256
274
    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));
 
275
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
276
                   gpgme_strsource(rc), gpgme_strerror(rc));
260
277
      return false;
261
278
    }
262
279
    
263
280
    rc = gpgme_op_import(mc.ctx, pgp_data);
264
281
    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));
 
282
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
283
                   gpgme_strsource(rc), gpgme_strerror(rc));
268
284
      return false;
269
285
    }
270
286
    
277
293
  }
278
294
  
279
295
  if(debug){
280
 
    fprintf(stderr, "Mandos plugin mandos-client: "
281
 
            "Initializing GPGME\n");
 
296
    fprintf_plus(stderr, "Initializing GPGME\n");
282
297
  }
283
298
  
284
299
  /* Init GPGME */
285
300
  gpgme_check_version(NULL);
286
301
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
287
302
  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));
 
303
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
304
                 gpgme_strsource(rc), gpgme_strerror(rc));
291
305
    return false;
292
306
  }
293
307
  
294
308
  /* Set GPGME home directory for the OpenPGP engine only */
295
309
  rc = gpgme_get_engine_info(&engine_info);
296
310
  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));
 
311
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
312
                 gpgme_strsource(rc), gpgme_strerror(rc));
300
313
    return false;
301
314
  }
302
315
  while(engine_info != NULL){
308
321
    engine_info = engine_info->next;
309
322
  }
310
323
  if(engine_info == NULL){
311
 
    fprintf(stderr, "Mandos plugin mandos-client: "
312
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
324
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
325
                 tempdir);
313
326
    return false;
314
327
  }
315
328
  
316
329
  /* Create new GPGME "context" */
317
330
  rc = gpgme_new(&(mc.ctx));
318
331
  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));
 
332
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
333
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
334
                 gpgme_strerror(rc));
322
335
    return false;
323
336
  }
324
337
  
343
356
  ssize_t plaintext_length = 0;
344
357
  
345
358
  if(debug){
346
 
    fprintf(stderr, "Mandos plugin mandos-client: "
347
 
            "Trying to decrypt OpenPGP data\n");
 
359
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
348
360
  }
349
361
  
350
362
  /* Create new GPGME data buffer from memory cryptotext */
351
363
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
352
364
                               0);
353
365
  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));
 
366
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
367
                 gpgme_strsource(rc), gpgme_strerror(rc));
357
368
    return -1;
358
369
  }
359
370
  
360
371
  /* Create new empty GPGME data buffer for the plaintext */
361
372
  rc = gpgme_data_new(&dh_plain);
362
373
  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));
 
374
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
375
                 "bad gpgme_data_new: %s: %s\n",
 
376
                 gpgme_strsource(rc), gpgme_strerror(rc));
366
377
    gpgme_data_release(dh_crypto);
367
378
    return -1;
368
379
  }
371
382
     data buffer */
372
383
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
373
384
  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));
 
385
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
386
                 gpgme_strsource(rc), gpgme_strerror(rc));
377
387
    plaintext_length = -1;
378
388
    if(debug){
379
389
      gpgme_decrypt_result_t result;
380
390
      result = gpgme_op_decrypt_result(mc.ctx);
381
391
      if(result == NULL){
382
 
        fprintf(stderr, "Mandos plugin mandos-client: "
383
 
                "gpgme_op_decrypt_result failed\n");
 
392
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
384
393
      } 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);
 
394
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
395
                     result->unsupported_algorithm);
 
396
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
397
                     result->wrong_key_usage);
391
398
        if(result->file_name != NULL){
392
 
          fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                  "File name: %s\n", result->file_name);
 
399
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
394
400
        }
395
401
        gpgme_recipient_t recipient;
396
402
        recipient = result->recipients;
397
403
        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");
 
404
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
405
                       gpgme_pubkey_algo_name
 
406
                       (recipient->pubkey_algo));
 
407
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
408
          fprintf_plus(stderr, "Secret key available: %s\n",
 
409
                       recipient->status == GPG_ERR_NO_SECKEY
 
410
                       ? "No" : "Yes");
407
411
          recipient = recipient->next;
408
412
        }
409
413
      }
412
416
  }
413
417
  
414
418
  if(debug){
415
 
    fprintf(stderr, "Mandos plugin mandos-client: "
416
 
            "Decryption of OpenPGP data succeeded\n");
 
419
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
417
420
  }
418
421
  
419
422
  /* Seek back to the beginning of the GPGME plaintext data buffer */
426
429
  *plaintext = NULL;
427
430
  while(true){
428
431
    plaintext_capacity = incbuffer(plaintext,
429
 
                                      (size_t)plaintext_length,
430
 
                                      plaintext_capacity);
 
432
                                   (size_t)plaintext_length,
 
433
                                   plaintext_capacity);
431
434
    if(plaintext_capacity == 0){
432
 
        perror_plus("incbuffer");
433
 
        plaintext_length = -1;
434
 
        goto decrypt_end;
 
435
      perror_plus("incbuffer");
 
436
      plaintext_length = -1;
 
437
      goto decrypt_end;
435
438
    }
436
439
    
437
440
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
450
453
  }
451
454
  
452
455
  if(debug){
453
 
    fprintf(stderr, "Mandos plugin mandos-client: "
454
 
            "Decrypted password is: ");
 
456
    fprintf_plus(stderr, "Decrypted password is: ");
455
457
    for(ssize_t i = 0; i < plaintext_length; i++){
456
458
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
457
459
    }
479
481
/* GnuTLS log function callback */
480
482
static void debuggnutls(__attribute__((unused)) int level,
481
483
                        const char* string){
482
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
484
  fprintf_plus(stderr, "GnuTLS: %s", string);
483
485
}
484
486
 
485
487
static int init_gnutls_global(const char *pubkeyfilename,
487
489
  int ret;
488
490
  
489
491
  if(debug){
490
 
    fprintf(stderr, "Mandos plugin mandos-client: "
491
 
            "Initializing GnuTLS\n");
 
492
    fprintf_plus(stderr, "Initializing GnuTLS\n");
492
493
  }
493
494
  
494
495
  ret = gnutls_global_init();
495
496
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "Mandos plugin mandos-client: "
497
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
497
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
498
                 safer_gnutls_strerror(ret));
498
499
    return -1;
499
500
  }
500
501
  
509
510
  /* OpenPGP credentials */
510
511
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
511
512
  if(ret != GNUTLS_E_SUCCESS){
512
 
    fprintf(stderr, "Mandos plugin mandos-client: "
513
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
513
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
514
                 safer_gnutls_strerror(ret));
514
515
    gnutls_global_deinit();
515
516
    return -1;
516
517
  }
517
518
  
518
519
  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);
 
520
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
521
                 " secret key %s as GnuTLS credentials\n",
 
522
                 pubkeyfilename,
 
523
                 seckeyfilename);
523
524
  }
524
525
  
525
526
  ret = gnutls_certificate_set_openpgp_key_file
526
527
    (mc.cred, pubkeyfilename, seckeyfilename,
527
528
     GNUTLS_OPENPGP_FMT_BASE64);
528
529
  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));
 
530
    fprintf_plus(stderr,
 
531
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
532
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
533
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
534
                 safer_gnutls_strerror(ret));
535
535
    goto globalfail;
536
536
  }
537
537
  
538
538
  /* GnuTLS server initialization */
539
539
  ret = gnutls_dh_params_init(&mc.dh_params);
540
540
  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));
 
541
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
542
                 " initialization: %s\n",
 
543
                 safer_gnutls_strerror(ret));
544
544
    goto globalfail;
545
545
  }
546
546
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
547
547
  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));
 
548
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
549
                 safer_gnutls_strerror(ret));
551
550
    goto globalfail;
552
551
  }
553
552
  
573
572
    }
574
573
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
575
574
  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));
 
575
    fprintf_plus(stderr,
 
576
                 "Error in GnuTLS session initialization: %s\n",
 
577
                 safer_gnutls_strerror(ret));
579
578
  }
580
579
  
581
580
  {
588
587
      }
589
588
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
590
589
    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));
 
590
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
591
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
592
                   safer_gnutls_strerror(ret));
595
593
      gnutls_deinit(*session);
596
594
      return -1;
597
595
    }
606
604
    }
607
605
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
608
606
  if(ret != GNUTLS_E_SUCCESS){
609
 
    fprintf(stderr, "Mandos plugin mandos-client: "
610
 
            "Error setting GnuTLS credentials: %s\n",
611
 
            safer_gnutls_strerror(ret));
 
607
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
608
                 safer_gnutls_strerror(ret));
612
609
    gnutls_deinit(*session);
613
610
    return -1;
614
611
  }
659
656
    pf = PF_INET;
660
657
    break;
661
658
  default:
662
 
    fprintf(stderr, "Mandos plugin mandos-client: "
663
 
            "Bad address family: %d\n", af);
 
659
    fprintf_plus(stderr, "Bad address family: %d\n", af);
664
660
    errno = EINVAL;
665
661
    return -1;
666
662
  }
671
667
  }
672
668
  
673
669
  if(debug){
674
 
    fprintf(stderr, "Mandos plugin mandos-client: "
675
 
            "Setting up a TCP connection to %s, port %" PRIu16
676
 
            "\n", ip, port);
 
670
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
671
                 PRIu16 "\n", ip, port);
677
672
  }
678
673
  
679
674
  tcp_sd = socket(pf, SOCK_STREAM, 0);
705
700
  }
706
701
  if(ret == 0){
707
702
    int e = errno;
708
 
    fprintf(stderr, "Mandos plugin mandos-client: "
709
 
            "Bad address: %s\n", ip);
 
703
    fprintf_plus(stderr, "Bad address: %s\n", ip);
710
704
    errno = e;
711
705
    goto mandos_end;
712
706
  }
717
711
    
718
712
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
719
713
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
720
 
                              -Wunreachable-code*/
 
714
                                -Wunreachable-code*/
721
715
      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");
 
716
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
717
                     " incomplete without a network interface\n");
725
718
        errno = EINVAL;
726
719
        goto mandos_end;
727
720
      }
745
738
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
746
739
        perror_plus("if_indextoname");
747
740
      } else {
748
 
        fprintf(stderr, "Mandos plugin mandos-client: "
749
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
750
 
                ip, interface, port);
 
741
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
742
                     "\n", ip, interface, port);
751
743
      }
752
744
    } else {
753
 
      fprintf(stderr, "Mandos plugin mandos-client: "
754
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
745
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
746
                   ip, port);
755
747
    }
756
748
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
757
749
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
767
759
      perror_plus("inet_ntop");
768
760
    } else {
769
761
      if(strcmp(addrstr, ip) != 0){
770
 
        fprintf(stderr, "Mandos plugin mandos-client: "
771
 
                "Canonical address form: %s\n", addrstr);
 
762
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
772
763
      }
773
764
    }
774
765
  }
802
793
  while(true){
803
794
    size_t out_size = strlen(out);
804
795
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
805
 
                                   out_size - written));
 
796
                                        out_size - written));
806
797
    if(ret == -1){
807
798
      int e = errno;
808
799
      perror_plus("write");
828
819
  }
829
820
  
830
821
  if(debug){
831
 
    fprintf(stderr, "Mandos plugin mandos-client: "
832
 
            "Establishing TLS session with %s\n", ip);
 
822
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
833
823
  }
834
824
  
835
825
  if(quit_now){
837
827
    goto mandos_end;
838
828
  }
839
829
  
840
 
  /* Spurious warning from -Wint-to-pointer-cast */
841
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
830
  /* This casting via intptr_t is to eliminate warning about casting
 
831
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
832
     function "set-session-transport-fd!" does it. */
 
833
  gnutls_transport_set_ptr(session,
 
834
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
842
835
  
843
836
  if(quit_now){
844
837
    errno = EINTR;
855
848
  
856
849
  if(ret != GNUTLS_E_SUCCESS){
857
850
    if(debug){
858
 
      fprintf(stderr, "Mandos plugin mandos-client: "
859
 
              "*** GnuTLS Handshake failed ***\n");
 
851
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
860
852
      gnutls_perror(ret);
861
853
    }
862
854
    errno = EPROTO;
866
858
  /* Read OpenPGP packet that contains the wanted password */
867
859
  
868
860
  if(debug){
869
 
    fprintf(stderr, "Mandos plugin mandos-client: "
870
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
861
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
862
                 " %s\n", ip);
871
863
  }
872
864
  
873
865
  while(true){
878
870
    }
879
871
    
880
872
    buffer_capacity = incbuffer(&buffer, buffer_length,
881
 
                                   buffer_capacity);
 
873
                                buffer_capacity);
882
874
    if(buffer_capacity == 0){
883
875
      int e = errno;
884
876
      perror_plus("incbuffer");
911
903
          }
912
904
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
913
905
        if(ret < 0){
914
 
          fprintf(stderr, "Mandos plugin mandos-client: "
915
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
906
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
907
                       "***\n");
916
908
          gnutls_perror(ret);
917
909
          errno = EPROTO;
918
910
          goto mandos_end;
919
911
        }
920
912
        break;
921
913
      default:
922
 
        fprintf(stderr, "Mandos plugin mandos-client: "
923
 
                "Unknown error while reading data from"
924
 
                " encrypted session with Mandos server\n");
 
914
        fprintf_plus(stderr, "Unknown error while reading data from"
 
915
                     " encrypted session with Mandos server\n");
925
916
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
926
917
        errno = EIO;
927
918
        goto mandos_end;
932
923
  }
933
924
  
934
925
  if(debug){
935
 
    fprintf(stderr, "Mandos plugin mandos-client: "
936
 
            "Closing TLS session\n");
 
926
    fprintf_plus(stderr, "Closing TLS session\n");
937
927
  }
938
928
  
939
929
  if(quit_now){
951
941
  
952
942
  if(buffer_length > 0){
953
943
    ssize_t decrypted_buffer_size;
954
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
955
 
                                               buffer_length,
 
944
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
956
945
                                               &decrypted_buffer);
957
946
    if(decrypted_buffer_size >= 0){
958
947
      
969
958
        if(ret == 0 and ferror(stdout)){
970
959
          int e = errno;
971
960
          if(debug){
972
 
            fprintf(stderr, "Mandos plugin mandos-client: "
973
 
                    "Error writing encrypted data: %s\n",
974
 
                    strerror(errno));
 
961
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
962
                         strerror(errno));
975
963
          }
976
964
          errno = e;
977
965
          goto mandos_end;
1034
1022
  switch(event){
1035
1023
  default:
1036
1024
  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)));
 
1025
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1026
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1027
                 domain,
 
1028
                 avahi_strerror(avahi_server_errno(mc.server)));
1041
1029
    break;
1042
1030
    
1043
1031
  case AVAHI_RESOLVER_FOUND:
1045
1033
      char ip[AVAHI_ADDRESS_STR_MAX];
1046
1034
      avahi_address_snprint(ip, sizeof(ip), address);
1047
1035
      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);
 
1036
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1037
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1038
                     host_name, ip, (intmax_t)interface, port);
1052
1039
      }
1053
1040
      int ret = start_mandos_communication(ip, port, interface,
1054
1041
                                           avahi_proto_to_af(proto));
1055
1042
      if(ret == 0){
1056
1043
        avahi_simple_poll_quit(mc.simple_poll);
1057
1044
      } else {
1058
 
        ret = add_server(ip, port, interface,
1059
 
                         avahi_proto_to_af(proto));
 
1045
        if(not add_server(ip, port, interface,
 
1046
                          avahi_proto_to_af(proto))){
 
1047
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1048
                       " list\n", name);
 
1049
        }
1060
1050
      }
1061
1051
    }
1062
1052
  }
1086
1076
  default:
1087
1077
  case AVAHI_BROWSER_FAILURE:
1088
1078
    
1089
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1090
 
            "(Avahi browser) %s\n",
1091
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1079
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1080
                 avahi_strerror(avahi_server_errno(mc.server)));
1092
1081
    avahi_simple_poll_quit(mc.simple_poll);
1093
1082
    return;
1094
1083
    
1101
1090
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1102
1091
                                    name, type, domain, protocol, 0,
1103
1092
                                    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)));
 
1093
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1094
                   " %s\n", name,
 
1095
                   avahi_strerror(avahi_server_errno(mc.server)));
1107
1096
    break;
1108
1097
    
1109
1098
  case AVAHI_BROWSER_REMOVE:
1112
1101
  case AVAHI_BROWSER_ALL_FOR_NOW:
1113
1102
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1114
1103
    if(debug){
1115
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1116
 
              "No Mandos server found, still searching...\n");
 
1104
      fprintf_plus(stderr, "No Mandos server found, still"
 
1105
                   " searching...\n");
1117
1106
    }
1118
1107
    break;
1119
1108
  }
1136
1125
 
1137
1126
bool get_flags(const char *ifname, struct ifreq *ifr){
1138
1127
  int ret;
 
1128
  error_t ret_errno;
1139
1129
  
1140
1130
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1141
1131
  if(s < 0){
 
1132
    ret_errno = errno;
1142
1133
    perror_plus("socket");
 
1134
    errno = ret_errno;
1143
1135
    return false;
1144
1136
  }
1145
1137
  strcpy(ifr->ifr_name, ifname);
1146
1138
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1147
1139
  if(ret == -1){
1148
1140
    if(debug){
 
1141
      ret_errno = errno;
1149
1142
      perror_plus("ioctl SIOCGIFFLAGS");
 
1143
      errno = ret_errno;
1150
1144
    }
1151
1145
    return false;
1152
1146
  }
1158
1152
  /* Reject the loopback device */
1159
1153
  if(ifr->ifr_flags & IFF_LOOPBACK){
1160
1154
    if(debug){
1161
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1162
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1155
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
                   ifname);
1163
1157
    }
1164
1158
    return false;
1165
1159
  }
1166
1160
  /* Accept point-to-point devices only if connect_to is specified */
1167
1161
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1168
1162
    if(debug){
1169
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1170
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1163
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1164
                   " \"%s\"\n", ifname);
1171
1165
    }
1172
1166
    return true;
1173
1167
  }
1174
1168
  /* Otherwise, reject non-broadcast-capable devices */
1175
1169
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1176
1170
    if(debug){
1177
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1178
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1171
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1172
                   " \"%s\"\n", ifname);
1179
1173
    }
1180
1174
    return false;
1181
1175
  }
1182
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
1183
1177
  if(ifr->ifr_flags & IFF_NOARP){
1184
1178
    if(debug){
1185
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1186
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1179
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
                   ifname);
1187
1181
    }
1188
1182
    return false;
1189
1183
  }
1190
1184
  
1191
1185
  /* Accept this device */
1192
1186
  if(debug){
1193
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1194
 
            "Interface \"%s\" is good\n", ifname);
 
1187
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1195
1188
  }
1196
1189
  return true;
1197
1190
}
1209
1202
  struct ifreq ifr;
1210
1203
  if(not get_flags(if_entry->d_name, &ifr)){
1211
1204
    if(debug){
1212
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1213
 
              "Failed to get flags for interface \"%s\"\n",
1214
 
              if_entry->d_name);
1215
 
    }
1216
 
    return 0;
1217
 
  }
1218
 
  
1219
 
  if(not good_flags(if_entry->d_name, &ifr)){
1220
 
    return 0;
1221
 
  }
1222
 
  return 1;
1223
 
}
1224
 
 
1225
 
/* 
1226
 
 * This function determines if a directory entry in /sys/class/net
1227
 
 * corresponds to an acceptable network device which is up.
1228
 
 * (This function is passed to scandir(3) as a filter function.)
1229
 
 */
1230
 
int up_interface(const struct dirent *if_entry){
1231
 
  if(if_entry->d_name[0] == '.'){
1232
 
    return 0;
1233
 
  }
1234
 
  
1235
 
  struct ifreq ifr;
1236
 
  if(not get_flags(if_entry->d_name, &ifr)){
1237
 
    if(debug){
1238
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1239
 
              "Failed to get flags for interface \"%s\"\n",
1240
 
              if_entry->d_name);
1241
 
    }
1242
 
    return 0;
1243
 
  }
1244
 
  
1245
 
  /* Reject down interfaces */
1246
 
  if(not (ifr.ifr_flags & IFF_UP)){
1247
 
    if(debug){
1248
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1249
 
              "Rejecting down interface \"%s\"\n",
1250
 
              if_entry->d_name);
1251
 
    }
1252
 
    return 0;
1253
 
  }
1254
 
  
1255
 
  /* Reject non-running interfaces */
1256
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1257
 
    if(debug){
1258
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1259
 
              "Rejecting non-running interface \"%s\"\n",
1260
 
              if_entry->d_name);
1261
 
    }
1262
 
    return 0;
1263
 
  }
1264
 
  
1265
 
  if(not good_flags(if_entry->d_name, &ifr)){
1266
 
    return 0;
1267
 
  }
1268
 
  return 1;
 
1205
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1206
                   "\"%s\"\n", if_entry->d_name);
 
1207
    }
 
1208
    return 0;
 
1209
  }
 
1210
  
 
1211
  if(not good_flags(if_entry->d_name, &ifr)){
 
1212
    return 0;
 
1213
  }
 
1214
  return 1;
 
1215
}
 
1216
 
 
1217
/* 
 
1218
 * This function determines if a network interface is up.
 
1219
 */
 
1220
bool interface_is_up(const char *interface){
 
1221
  struct ifreq ifr;
 
1222
  if(not get_flags(interface, &ifr)){
 
1223
    if(debug){
 
1224
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1225
                   "\"%s\"\n", interface);
 
1226
    }
 
1227
    return false;
 
1228
  }
 
1229
  
 
1230
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1231
}
 
1232
 
 
1233
/* 
 
1234
 * This function determines if a network interface is running
 
1235
 */
 
1236
bool interface_is_running(const char *interface){
 
1237
  struct ifreq ifr;
 
1238
  if(not get_flags(interface, &ifr)){
 
1239
    if(debug){
 
1240
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1241
                   "\"%s\"\n", interface);
 
1242
    }
 
1243
    return false;
 
1244
  }
 
1245
  
 
1246
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1269
1247
}
1270
1248
 
1271
1249
int notdotentries(const struct dirent *direntry){
1282
1260
/* Is this directory entry a runnable program? */
1283
1261
int runnable_hook(const struct dirent *direntry){
1284
1262
  int ret;
 
1263
  size_t sret;
1285
1264
  struct stat st;
1286
1265
  
1287
1266
  if((direntry->d_name)[0] == '\0'){
1289
1268
    return 0;
1290
1269
  }
1291
1270
  
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 */
 
1271
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1272
                "abcdefghijklmnopqrstuvwxyz"
 
1273
                "0123456789"
 
1274
                "_-");
 
1275
  if((direntry->d_name)[sret] != '\0'){
 
1276
    /* Contains non-allowed characters */
 
1277
    if(debug){
 
1278
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1279
                   direntry->d_name);
 
1280
    }
 
1281
    return 0;
 
1282
  }
1307
1283
  
1308
1284
  char *fullname = NULL;
1309
 
  ret = asprintf(&fullname, "%s/%s", hookdir,
1310
 
                 direntry->d_name);
 
1285
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1311
1286
  if(ret < 0){
1312
1287
    perror_plus("asprintf");
1313
1288
    return 0;
1316
1291
  ret = stat(fullname, &st);
1317
1292
  if(ret == -1){
1318
1293
    if(debug){
1319
 
      perror_plus("Could not stat plugin");
 
1294
      perror_plus("Could not stat hook");
1320
1295
    }
1321
1296
    return 0;
1322
1297
  }
1323
1298
  if(not (S_ISREG(st.st_mode))){
1324
1299
    /* Not a regular file */
 
1300
    if(debug){
 
1301
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1302
                   direntry->d_name);
 
1303
    }
1325
1304
    return 0;
1326
1305
  }
1327
1306
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1328
1307
    /* Not executable */
 
1308
    if(debug){
 
1309
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1310
                   direntry->d_name);
 
1311
    }
1329
1312
    return 0;
1330
1313
  }
 
1314
  if(debug){
 
1315
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1316
                 direntry->d_name);
 
1317
  }
1331
1318
  return 1;
1332
1319
}
1333
1320
 
1340
1327
  while(true){
1341
1328
    if(mc.current_server == NULL){
1342
1329
      if (debug){
1343
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1344
 
                "Wait until first server is found. No timeout!\n");
 
1330
        fprintf_plus(stderr, "Wait until first server is found."
 
1331
                     " No timeout!\n");
1345
1332
      }
1346
1333
      ret = avahi_simple_poll_iterate(s, -1);
1347
1334
    } else {
1348
1335
      if (debug){
1349
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1350
 
                "Check current_server if we should run it,"
1351
 
                " or wait\n");
 
1336
        fprintf_plus(stderr, "Check current_server if we should run"
 
1337
                     " it, or wait\n");
1352
1338
      }
1353
1339
      /* the current time */
1354
1340
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1370
1356
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1371
1357
      
1372
1358
      if (debug){
1373
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1374
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1359
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1360
                     block_time);
1375
1361
      }
1376
1362
      
1377
1363
      if(block_time <= 0){
1404
1390
  }
1405
1391
}
1406
1392
 
 
1393
/* Set effective uid to 0, return errno */
 
1394
error_t raise_privileges(void){
 
1395
  error_t old_errno = errno;
 
1396
  error_t ret_errno = 0;
 
1397
  if(seteuid(0) == -1){
 
1398
    ret_errno = errno;
 
1399
    perror_plus("seteuid");
 
1400
  }
 
1401
  errno = old_errno;
 
1402
  return ret_errno;
 
1403
}
 
1404
 
 
1405
/* Set effective and real user ID to 0.  Return errno. */
 
1406
error_t raise_privileges_permanently(void){
 
1407
  error_t old_errno = errno;
 
1408
  error_t ret_errno = raise_privileges();
 
1409
  if(ret_errno != 0){
 
1410
    errno = old_errno;
 
1411
    return ret_errno;
 
1412
  }
 
1413
  if(setuid(0) == -1){
 
1414
    ret_errno = errno;
 
1415
    perror_plus("seteuid");
 
1416
  }
 
1417
  errno = old_errno;
 
1418
  return ret_errno;
 
1419
}
 
1420
 
 
1421
/* Set effective user ID to unprivileged saved user ID */
 
1422
error_t lower_privileges(void){
 
1423
  error_t old_errno = errno;
 
1424
  error_t ret_errno = 0;
 
1425
  if(seteuid(uid) == -1){
 
1426
    ret_errno = errno;
 
1427
    perror_plus("seteuid");
 
1428
  }
 
1429
  errno = old_errno;
 
1430
  return ret_errno;
 
1431
}
 
1432
 
 
1433
/* Lower privileges permanently */
 
1434
error_t lower_privileges_permanently(void){
 
1435
  error_t old_errno = errno;
 
1436
  error_t ret_errno = 0;
 
1437
  if(setuid(uid) == -1){
 
1438
    ret_errno = errno;
 
1439
    perror_plus("setuid");
 
1440
  }
 
1441
  errno = old_errno;
 
1442
  return ret_errno;
 
1443
}
 
1444
 
 
1445
bool run_network_hooks(const char *mode, const char *interface,
 
1446
                       const float delay){
 
1447
  struct dirent **direntries;
 
1448
  struct dirent *direntry;
 
1449
  int ret;
 
1450
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1451
                         alphasort);
 
1452
  if(numhooks == -1){
 
1453
    perror_plus("scandir");
 
1454
  } else {
 
1455
    int devnull = open("/dev/null", O_RDONLY);
 
1456
    for(int i = 0; i < numhooks; i++){
 
1457
      direntry = direntries[i];
 
1458
      char *fullname = NULL;
 
1459
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1460
      if(ret < 0){
 
1461
        perror_plus("asprintf");
 
1462
        continue;
 
1463
      }
 
1464
      if(debug){
 
1465
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1466
                     direntry->d_name);
 
1467
      }
 
1468
      pid_t hook_pid = fork();
 
1469
      if(hook_pid == 0){
 
1470
        /* Child */
 
1471
        /* Raise privileges */
 
1472
        raise_privileges_permanently();
 
1473
        /* Set group */
 
1474
        errno = 0;
 
1475
        ret = setgid(0);
 
1476
        if(ret == -1){
 
1477
          perror_plus("setgid");
 
1478
        }
 
1479
        /* Reset supplementary groups */
 
1480
        errno = 0;
 
1481
        ret = setgroups(0, NULL);
 
1482
        if(ret == -1){
 
1483
          perror_plus("setgroups");
 
1484
        }
 
1485
        dup2(devnull, STDIN_FILENO);
 
1486
        close(devnull);
 
1487
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1488
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1489
        if(ret == -1){
 
1490
          perror_plus("setenv");
 
1491
          _exit(EX_OSERR);
 
1492
        }
 
1493
        ret = setenv("DEVICE", interface, 1);
 
1494
        if(ret == -1){
 
1495
          perror_plus("setenv");
 
1496
          _exit(EX_OSERR);
 
1497
        }
 
1498
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1499
        if(ret == -1){
 
1500
          perror_plus("setenv");
 
1501
          _exit(EX_OSERR);
 
1502
        }
 
1503
        ret = setenv("MODE", mode, 1);
 
1504
        if(ret == -1){
 
1505
          perror_plus("setenv");
 
1506
          _exit(EX_OSERR);
 
1507
        }
 
1508
        char *delaystring;
 
1509
        ret = asprintf(&delaystring, "%f", delay);
 
1510
        if(ret == -1){
 
1511
          perror_plus("asprintf");
 
1512
          _exit(EX_OSERR);
 
1513
        }
 
1514
        ret = setenv("DELAY", delaystring, 1);
 
1515
        if(ret == -1){
 
1516
          free(delaystring);
 
1517
          perror_plus("setenv");
 
1518
          _exit(EX_OSERR);
 
1519
        }
 
1520
        free(delaystring);
 
1521
        if(connect_to != NULL){
 
1522
          ret = setenv("CONNECT", connect_to, 1);
 
1523
          if(ret == -1){
 
1524
            perror_plus("setenv");
 
1525
            _exit(EX_OSERR);
 
1526
          }
 
1527
        }
 
1528
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
 
1529
          perror_plus("execl");
 
1530
          _exit(EXIT_FAILURE);
 
1531
        }
 
1532
      } else {
 
1533
        int status;
 
1534
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1535
          perror_plus("waitpid");
 
1536
          free(fullname);
 
1537
          continue;
 
1538
        }
 
1539
        if(WIFEXITED(status)){
 
1540
          if(WEXITSTATUS(status) != 0){
 
1541
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1542
                         " with status %d\n", direntry->d_name,
 
1543
                         WEXITSTATUS(status));
 
1544
            free(fullname);
 
1545
            continue;
 
1546
          }
 
1547
        } else if(WIFSIGNALED(status)){
 
1548
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1549
                       " signal %d\n", direntry->d_name,
 
1550
                       WTERMSIG(status));
 
1551
          free(fullname);
 
1552
          continue;
 
1553
        } else {
 
1554
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1555
                       " crashed\n", direntry->d_name);
 
1556
          free(fullname);
 
1557
          continue;
 
1558
        }
 
1559
      }
 
1560
      free(fullname);
 
1561
      if(debug){
 
1562
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1563
                     direntry->d_name);
 
1564
      }
 
1565
    }
 
1566
    close(devnull);
 
1567
  }
 
1568
  return true;
 
1569
}
 
1570
 
 
1571
error_t bring_up_interface(const char *const interface,
 
1572
                           const float delay){
 
1573
  int sd = -1;
 
1574
  error_t old_errno = errno;
 
1575
  error_t ret_errno = 0;
 
1576
  int ret, ret_setflags;
 
1577
  struct ifreq network;
 
1578
  unsigned int if_index = if_nametoindex(interface);
 
1579
  if(if_index == 0){
 
1580
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1581
    errno = old_errno;
 
1582
    return ENXIO;
 
1583
  }
 
1584
  
 
1585
  if(quit_now){
 
1586
    errno = old_errno;
 
1587
    return EINTR;
 
1588
  }
 
1589
  
 
1590
  if(not interface_is_up(interface)){
 
1591
    if(not get_flags(interface, &network) and debug){
 
1592
      ret_errno = errno;
 
1593
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1594
                   "\"%s\"\n", interface);
 
1595
      return ret_errno;
 
1596
    }
 
1597
    network.ifr_flags |= IFF_UP;
 
1598
    
 
1599
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1600
    if(sd < 0){
 
1601
      ret_errno = errno;
 
1602
      perror_plus("socket");
 
1603
      errno = old_errno;
 
1604
      return ret_errno;
 
1605
    }
 
1606
  
 
1607
    if(quit_now){
 
1608
      close(sd);
 
1609
      errno = old_errno;
 
1610
      return EINTR;
 
1611
    }
 
1612
    
 
1613
    if(debug){
 
1614
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1615
                   interface);
 
1616
    }
 
1617
    
 
1618
    /* Raise priviliges */
 
1619
    raise_privileges();
 
1620
    
 
1621
#ifdef __linux__
 
1622
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1623
       messages about the network interface to mess up the prompt */
 
1624
    int ret_linux = klogctl(8, NULL, 5);
 
1625
    bool restore_loglevel = true;
 
1626
    if(ret_linux == -1){
 
1627
      restore_loglevel = false;
 
1628
      perror_plus("klogctl");
 
1629
    }
 
1630
#endif  /* __linux__ */
 
1631
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1632
    ret_errno = errno;
 
1633
#ifdef __linux__
 
1634
    if(restore_loglevel){
 
1635
      ret_linux = klogctl(7, NULL, 0);
 
1636
      if(ret_linux == -1){
 
1637
        perror_plus("klogctl");
 
1638
      }
 
1639
    }
 
1640
#endif  /* __linux__ */
 
1641
    
 
1642
    /* Lower privileges */
 
1643
    lower_privileges();
 
1644
    
 
1645
    /* Close the socket */
 
1646
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1647
    if(ret == -1){
 
1648
      perror_plus("close");
 
1649
    }
 
1650
    
 
1651
    if(ret_setflags == -1){
 
1652
      errno = ret_errno;
 
1653
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1654
      errno = old_errno;
 
1655
      return ret_errno;
 
1656
    }
 
1657
  } else if(debug){
 
1658
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1659
                 interface);
 
1660
  }
 
1661
  
 
1662
  /* Sleep checking until interface is running.
 
1663
     Check every 0.25s, up to total time of delay */
 
1664
  for(int i=0; i < delay * 4; i++){
 
1665
    if(interface_is_running(interface)){
 
1666
      break;
 
1667
    }
 
1668
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1669
    ret = nanosleep(&sleeptime, NULL);
 
1670
    if(ret == -1 and errno != EINTR){
 
1671
      perror_plus("nanosleep");
 
1672
    }
 
1673
  }
 
1674
  
 
1675
  errno = old_errno;
 
1676
  return 0;
 
1677
}
 
1678
 
 
1679
error_t take_down_interface(const char *const interface){
 
1680
  int sd = -1;
 
1681
  error_t old_errno = errno;
 
1682
  error_t ret_errno = 0;
 
1683
  int ret, ret_setflags;
 
1684
  struct ifreq network;
 
1685
  unsigned int if_index = if_nametoindex(interface);
 
1686
  if(if_index == 0){
 
1687
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1688
    errno = old_errno;
 
1689
    return ENXIO;
 
1690
  }
 
1691
  if(interface_is_up(interface)){
 
1692
    if(not get_flags(interface, &network) and debug){
 
1693
      ret_errno = errno;
 
1694
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1695
                   "\"%s\"\n", interface);
 
1696
      return ret_errno;
 
1697
    }
 
1698
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1699
    
 
1700
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1701
    if(sd < 0){
 
1702
      ret_errno = errno;
 
1703
      perror_plus("socket");
 
1704
      errno = old_errno;
 
1705
      return ret_errno;
 
1706
    }
 
1707
    
 
1708
    if(debug){
 
1709
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1710
                   interface);
 
1711
    }
 
1712
    
 
1713
    /* Raise priviliges */
 
1714
    raise_privileges();
 
1715
    
 
1716
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1717
    ret_errno = errno;
 
1718
    
 
1719
    /* Lower privileges */
 
1720
    lower_privileges();
 
1721
    
 
1722
    /* Close the socket */
 
1723
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1724
    if(ret == -1){
 
1725
      perror_plus("close");
 
1726
    }
 
1727
    
 
1728
    if(ret_setflags == -1){
 
1729
      errno = ret_errno;
 
1730
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1731
      errno = old_errno;
 
1732
      return ret_errno;
 
1733
    }
 
1734
  } else if(debug){
 
1735
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1736
                 interface);
 
1737
  }
 
1738
  
 
1739
  errno = old_errno;
 
1740
  return 0;
 
1741
}
 
1742
 
1407
1743
int main(int argc, char *argv[]){
1408
1744
  AvahiSServiceBrowser *sb = NULL;
1409
 
  int error;
 
1745
  error_t ret_errno;
1410
1746
  int ret;
1411
1747
  intmax_t tmpmax;
1412
1748
  char *tmp;
1413
1749
  int exitcode = EXIT_SUCCESS;
1414
 
  const char *interface = "";
1415
 
  struct ifreq network;
1416
 
  int sd = -1;
1417
 
  bool take_down_interface = false;
1418
 
  uid_t uid;
1419
 
  gid_t gid;
 
1750
  char *interfaces = NULL;
 
1751
  size_t interfaces_size = 0;
 
1752
  char *interfaces_to_take_down = NULL;
 
1753
  size_t interfaces_to_take_down_size = 0;
1420
1754
  char tempdir[] = "/tmp/mandosXXXXXX";
1421
1755
  bool tempdir_created = false;
1422
1756
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1423
1757
  const char *seckey = PATHDIR "/" SECKEY;
1424
1758
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1759
  char *interfaces_hooks = NULL;
 
1760
  size_t interfaces_hooks_size = 0;
1425
1761
  
1426
1762
  bool gnutls_initialized = false;
1427
1763
  bool gpgme_initialized = false;
1489
1825
        .group = 2 },
1490
1826
      { .name = "retry", .key = 132,
1491
1827
        .arg = "SECONDS",
1492
 
        .doc = "Retry interval used when denied by the mandos server",
 
1828
        .doc = "Retry interval used when denied by the Mandos server",
1493
1829
        .group = 2 },
1494
1830
      { .name = "network-hook-dir", .key = 133,
1495
1831
        .arg = "DIR",
1518
1854
        connect_to = arg;
1519
1855
        break;
1520
1856
      case 'i':                 /* --interface */
1521
 
        interface = arg;
 
1857
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
 
1858
                                 (int)',');
 
1859
        if(ret_errno != 0){
 
1860
          argp_error(state, "%s", strerror(ret_errno));
 
1861
        }
1522
1862
        break;
1523
1863
      case 's':                 /* --seckey */
1524
1864
        seckey = arg;
1567
1907
        argp_state_help(state, state->out_stream,
1568
1908
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1569
1909
      case 'V':                 /* --version */
1570
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1571
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1910
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1572
1911
        exit(argp_err_exit_status);
1573
1912
        break;
1574
1913
      default:
1601
1940
  {
1602
1941
    /* Work around Debian bug #633582:
1603
1942
       <http://bugs.debian.org/633582> */
1604
 
    struct stat st;
1605
1943
    
1606
1944
    /* 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");
1658
 
    }
1659
 
  }
1660
 
  
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);
 
1945
    if(raise_privileges() == 0){
 
1946
      struct stat st;
 
1947
      
 
1948
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1949
        int seckey_fd = open(seckey, O_RDONLY);
 
1950
        if(seckey_fd == -1){
 
1951
          perror_plus("open");
 
1952
        } else {
 
1953
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1954
          if(ret == -1){
 
1955
            perror_plus("fstat");
 
1956
          } else {
 
1957
            if(S_ISREG(st.st_mode)
 
1958
               and st.st_uid == 0 and st.st_gid == 0){
 
1959
              ret = fchown(seckey_fd, uid, gid);
 
1960
              if(ret == -1){
 
1961
                perror_plus("fchown");
 
1962
              }
 
1963
            }
 
1964
          }
 
1965
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
1966
        }
 
1967
      }
 
1968
    
 
1969
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1970
        int pubkey_fd = open(pubkey, O_RDONLY);
 
1971
        if(pubkey_fd == -1){
 
1972
          perror_plus("open");
 
1973
        } else {
 
1974
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1975
          if(ret == -1){
 
1976
            perror_plus("fstat");
 
1977
          } else {
 
1978
            if(S_ISREG(st.st_mode)
 
1979
               and st.st_uid == 0 and st.st_gid == 0){
 
1980
              ret = fchown(pubkey_fd, uid, gid);
 
1981
              if(ret == -1){
 
1982
                perror_plus("fchown");
 
1983
              }
 
1984
            }
 
1985
          }
 
1986
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1987
        }
 
1988
      }
 
1989
    
 
1990
      /* Lower privileges */
 
1991
      errno = 0;
 
1992
      ret = seteuid(uid);
 
1993
      if(ret == -1){
 
1994
        perror_plus("seteuid");
 
1995
      }
 
1996
    }
 
1997
  }
 
1998
  
 
1999
  /* Remove empty interface names */
 
2000
  {
 
2001
    char *interface = NULL;
 
2002
    while((interface = argz_next(interfaces, interfaces_size,
 
2003
                                 interface))){
 
2004
      if(if_nametoindex(interface) == 0){
 
2005
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
 
2006
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2007
                       " \"%s\"\n", interface);
 
2008
        }
 
2009
        argz_delete(&interfaces, &interfaces_size, interface);
 
2010
        interface = NULL;
 
2011
      }
 
2012
    }
 
2013
  }
 
2014
  
 
2015
  /* Run network hooks */
 
2016
  {
 
2017
    ret_errno = argz_append(&interfaces_hooks, &interfaces_hooks_size,
 
2018
                            interfaces, interfaces_size);
 
2019
    if(ret_errno != 0){
 
2020
      errno = ret_errno;
 
2021
      perror_plus("argz_append");
 
2022
      goto end;
 
2023
    }
 
2024
    argz_stringify(interfaces_hooks, interfaces_hooks_size, (int)',');
 
2025
    if(not run_network_hooks("start", interfaces_hooks, delay)){
 
2026
      goto end;
1752
2027
    }
1753
2028
  }
1754
2029
  
1756
2031
    avahi_set_log_function(empty_log);
1757
2032
  }
1758
2033
  
1759
 
  if(interface[0] == '\0'){
1760
 
    struct dirent **direntries;
1761
 
    /* First look for interfaces that are up */
1762
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1763
 
                  alphasort);
1764
 
    if(ret == 0){
1765
 
      /* No up interfaces, look for any good interfaces */
1766
 
      free(direntries);
1767
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1768
 
                    alphasort);
1769
 
    }
1770
 
    if(ret >= 1){
1771
 
      /* Pick the first interface returned */
1772
 
      interface = strdup(direntries[0]->d_name);
1773
 
      if(debug){
1774
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1775
 
                "Using interface \"%s\"\n", interface);
1776
 
      }
1777
 
      if(interface == NULL){
1778
 
        perror_plus("malloc");
1779
 
        free(direntries);
1780
 
        exitcode = EXIT_FAILURE;
1781
 
        goto end;
1782
 
      }
1783
 
      free(direntries);
1784
 
    } else {
1785
 
      free(direntries);
1786
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1787
 
              "Could not find a network interface\n");
1788
 
      exitcode = EXIT_FAILURE;
1789
 
      goto end;
1790
 
    }
1791
 
  }
1792
 
  
1793
2034
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1794
2035
     from the signal handler */
1795
2036
  /* Initialize the pseudo-RNG for Avahi */
1796
2037
  srand((unsigned int) time(NULL));
1797
2038
  mc.simple_poll = avahi_simple_poll_new();
1798
2039
  if(mc.simple_poll == NULL){
1799
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1800
 
            "Avahi: Failed to create simple poll object.\n");
 
2040
    fprintf_plus(stderr,
 
2041
                 "Avahi: Failed to create simple poll object.\n");
1801
2042
    exitcode = EX_UNAVAILABLE;
1802
2043
    goto end;
1803
2044
  }
1865
2106
    }
1866
2107
  }
1867
2108
  
1868
 
  /* 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
 
      }
 
2109
  /* If no interfaces were specified, make a list */
 
2110
  if(interfaces == NULL){
 
2111
    struct dirent **direntries;
 
2112
    /* Look for any good interfaces */
 
2113
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2114
                  alphasort);
 
2115
    if(ret >= 1){
 
2116
      /* Add all found interfaces to interfaces list */
 
2117
      for(int i = 0; i < ret; ++i){
 
2118
        ret_errno = argz_add(&interfaces, &interfaces_size,
 
2119
                             direntries[i]->d_name);
 
2120
        if(ret_errno != 0){
 
2121
          perror_plus("argz_add");
 
2122
          continue;
 
2123
        }
 
2124
        if(debug){
 
2125
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2126
                       direntries[i]->d_name);
 
2127
        }
 
2128
      }
 
2129
      free(direntries);
2005
2130
    } else {
2006
 
      /* Lower privileges permanently */
2007
 
      ret = setuid(uid);
2008
 
      if(ret == -1){
2009
 
        perror_plus("setuid");
 
2131
      free(direntries);
 
2132
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2133
      exitcode = EXIT_FAILURE;
 
2134
      goto end;
 
2135
    }
 
2136
  }
 
2137
  
 
2138
  /* If we only got one interface, explicitly use only that one */
 
2139
  if(argz_count(interfaces, interfaces_size) == 1){
 
2140
    if(debug){
 
2141
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2142
                   interfaces);
 
2143
    }
 
2144
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
 
2145
  }
 
2146
  
 
2147
  /* Bring up interfaces which are down */
 
2148
  if(not (argz_count(interfaces, interfaces_size) == 1
 
2149
          and strcmp(interfaces, "none") == 0)){
 
2150
    char *interface = NULL;
 
2151
    while((interface = argz_next(interfaces, interfaces_size,
 
2152
                                 interface))){
 
2153
      bool interface_was_up = interface_is_up(interface);
 
2154
      ret = bring_up_interface(interface, delay);
 
2155
      if(not interface_was_up){
 
2156
        if(ret != 0){
 
2157
          errno = ret;
 
2158
          perror_plus("Failed to bring up interface");
 
2159
        } else {
 
2160
          ret_errno = argz_add(&interfaces_to_take_down,
 
2161
                               &interfaces_to_take_down_size,
 
2162
                               interface);
 
2163
        }
2010
2164
      }
2011
2165
    }
 
2166
    free(interfaces);
 
2167
    interfaces = NULL;
 
2168
    interfaces_size = 0;
 
2169
    if(debug and (interfaces_to_take_down == NULL)){
 
2170
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2171
    }
2012
2172
  }
2013
2173
  
2014
2174
  if(quit_now){
2017
2177
  
2018
2178
  ret = init_gnutls_global(pubkey, seckey);
2019
2179
  if(ret == -1){
2020
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2021
 
            "init_gnutls_global failed\n");
 
2180
    fprintf_plus(stderr, "init_gnutls_global failed\n");
2022
2181
    exitcode = EX_UNAVAILABLE;
2023
2182
    goto end;
2024
2183
  } else {
2040
2199
  }
2041
2200
  
2042
2201
  if(not init_gpgme(pubkey, seckey, tempdir)){
2043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2044
 
            "init_gpgme failed\n");
 
2202
    fprintf_plus(stderr, "init_gpgme failed\n");
2045
2203
    exitcode = EX_UNAVAILABLE;
2046
2204
    goto end;
2047
2205
  } else {
2056
2214
    /* Connect directly, do not use Zeroconf */
2057
2215
    /* (Mainly meant for debugging) */
2058
2216
    char *address = strrchr(connect_to, ':');
 
2217
    
2059
2218
    if(address == NULL){
2060
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2061
 
              "No colon in address\n");
 
2219
      fprintf_plus(stderr, "No colon in address\n");
2062
2220
      exitcode = EX_USAGE;
2063
2221
      goto end;
2064
2222
    }
2072
2230
    tmpmax = strtoimax(address+1, &tmp, 10);
2073
2231
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2074
2232
       or tmpmax != (uint16_t)tmpmax){
2075
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2076
 
              "Bad port number\n");
 
2233
      fprintf_plus(stderr, "Bad port number\n");
2077
2234
      exitcode = EX_USAGE;
2078
2235
      goto end;
2079
2236
    }
2109
2266
        break;
2110
2267
      }
2111
2268
      if(debug){
2112
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2113
 
                "Retrying in %d seconds\n", (int)retry_interval);
 
2269
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2270
                     (int)retry_interval);
2114
2271
      }
2115
2272
      sleep((int)retry_interval);
2116
2273
    }
2138
2295
    /* Allocate a new server */
2139
2296
    mc.server = avahi_server_new(avahi_simple_poll_get
2140
2297
                                 (mc.simple_poll), &config, NULL,
2141
 
                                 NULL, &error);
 
2298
                                 NULL, &ret_errno);
2142
2299
    
2143
2300
    /* Free the Avahi configuration data */
2144
2301
    avahi_server_config_free(&config);
2146
2303
  
2147
2304
  /* Check if creating the Avahi server object succeeded */
2148
2305
  if(mc.server == NULL){
2149
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2150
 
            "Failed to create Avahi server: %s\n",
2151
 
            avahi_strerror(error));
 
2306
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2307
                 avahi_strerror(ret_errno));
2152
2308
    exitcode = EX_UNAVAILABLE;
2153
2309
    goto end;
2154
2310
  }
2162
2318
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2163
2319
                                   NULL, 0, browse_callback, NULL);
2164
2320
  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)));
 
2321
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2322
                 avahi_strerror(avahi_server_errno(mc.server)));
2168
2323
    exitcode = EX_UNAVAILABLE;
2169
2324
    goto end;
2170
2325
  }
2176
2331
  /* Run the main loop */
2177
2332
  
2178
2333
  if(debug){
2179
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2180
 
            "Starting Avahi loop search\n");
 
2334
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2181
2335
  }
2182
2336
 
2183
2337
  ret = avahi_loop_with_timeout(mc.simple_poll,
2184
2338
                                (int)(retry_interval * 1000));
2185
2339
  if(debug){
2186
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2187
 
            "avahi_loop_with_timeout exited %s\n",
2188
 
            (ret == 0) ? "successfully" : "with error");
 
2340
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2341
                 (ret == 0) ? "successfully" : "with error");
2189
2342
  }
2190
2343
  
2191
2344
 end:
2192
2345
  
2193
2346
  if(debug){
2194
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2195
 
            "%s exiting\n", argv[0]);
 
2347
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2196
2348
  }
2197
2349
  
2198
2350
  /* Cleanup things */
2214
2366
  if(gpgme_initialized){
2215
2367
    gpgme_release(mc.ctx);
2216
2368
  }
2217
 
 
 
2369
  
2218
2370
  /* Cleans up the circular linked list of Mandos servers the client
2219
2371
     has seen */
2220
2372
  if(mc.current_server != NULL){
2226
2378
    }
2227
2379
  }
2228
2380
  
2229
 
  /* XXX run network hooks "stop" here  */
2230
 
  
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){
2240
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2241
 
      if(ret == -1){
2242
 
        perror_plus("ioctl SIOCGIFFLAGS");
2243
 
      } else if(network.ifr_flags & IFF_UP){
2244
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2245
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2246
 
        if(ret == -1){
2247
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2381
  /* Re-raise priviliges */
 
2382
  {
 
2383
    raise_privileges();
 
2384
    
 
2385
    /* Run network hooks */
 
2386
    run_network_hooks("stop", interfaces_hooks, delay);
 
2387
    
 
2388
    /* Take down the network interfaces which were brought up */
 
2389
    {
 
2390
      char *interface = NULL;
 
2391
      while((interface=argz_next(interfaces_to_take_down,
 
2392
                                 interfaces_to_take_down_size,
 
2393
                                 interface))){
 
2394
        ret_errno = take_down_interface(interface);
 
2395
        if(ret_errno != 0){
 
2396
          errno = ret_errno;
 
2397
          perror_plus("Failed to take down interface");
2248
2398
        }
2249
2399
      }
2250
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2251
 
      if(ret == -1){
2252
 
        perror_plus("close");
2253
 
      }
2254
 
      /* Lower privileges permanently */
2255
 
      errno = 0;
2256
 
      ret = setuid(uid);
2257
 
      if(ret == -1){
2258
 
        perror_plus("setuid");
 
2400
      if(debug and (interfaces_to_take_down == NULL)){
 
2401
        fprintf_plus(stderr, "No interfaces needed to be taken"
 
2402
                     " down\n");
2259
2403
      }
2260
2404
    }
 
2405
    
 
2406
    lower_privileges_permanently();
2261
2407
  }
2262
2408
  
 
2409
  free(interfaces_to_take_down);
 
2410
  free(interfaces_hooks);
 
2411
  
2263
2412
  /* Removes the GPGME temp directory and all files inside */
2264
2413
  if(tempdir_created){
2265
2414
    struct dirent **direntries = NULL;
2278
2427
        }
2279
2428
        ret = remove(fullname);
2280
2429
        if(ret == -1){
2281
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2282
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2430
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2431
                       strerror(errno));
2283
2432
        }
2284
2433
        free(fullname);
2285
2434
      }