/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: 2010-09-25 23:52:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100925235217-4hhqfryz1ste6uw3
* mandos (ClientDBus.__init__): Bug fix: Translate "-" in client names
                                to "_" in D-Bus object paths.
  (MandosServer.handle_ipc): Bug fix: Send only address string to
                             D-Bus signal, not whole tuple.

* mandos-ctl: New options "--approve-by-default", "--deny-by-default",
              "--approval-delay", and "--approval-duration".
* mandos-ctl.xml (SYNOPSIS, OPTIONS): Document new options.

* mandos-monitor (MandosClientWidget.update): Fix spelling.

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,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 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
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
 
65
#include <errno.h>              /* perror(), errno */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
75
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
85
84
                                   raise() */
86
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
87
 
91
88
#ifdef __linux__
92
89
#include <sys/klog.h>           /* klogctl() */
125
122
#define PATHDIR "/conf/conf.d/mandos"
126
123
#define SECKEY "seckey.txt"
127
124
#define PUBKEY "pubkey.txt"
128
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
129
125
 
130
126
bool debug = false;
131
127
static const char mandos_protocol_version[] = "1";
132
128
const char *argp_program_version = "mandos-client " VERSION;
133
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
134
130
static const char sys_class_net[] = "/sys/class/net";
135
131
char *connect_to = NULL;
136
 
const char *hookdir = HOOKDIR;
137
 
 
138
 
/* Doubly linked list that need to be circularly linked when used */
139
 
typedef struct server{
140
 
  const char *ip;
141
 
  uint16_t port;
142
 
  AvahiIfIndex if_index;
143
 
  int af;
144
 
  struct timespec last_seen;
145
 
  struct server *next;
146
 
  struct server *prev;
147
 
} server;
148
132
 
149
133
/* Used for passing in values through the Avahi callback functions */
150
134
typedef struct {
155
139
  gnutls_dh_params_t dh_params;
156
140
  const char *priority;
157
141
  gpgme_ctx_t ctx;
158
 
  server *current_server;
159
142
} mandos_context;
160
143
 
161
144
/* global context so signal handler can reach it*/
162
145
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
146
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
147
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
166
148
 
167
149
sig_atomic_t quit_now = 0;
168
150
int signal_received = 0;
169
151
 
170
 
/* Function to use when printing errors */
171
 
void perror_plus(const char *print_text){
172
 
  fprintf(stderr, "Mandos plugin %s: ",
173
 
          program_invocation_short_name);
174
 
  perror(print_text);
175
 
}
176
 
 
177
152
/*
178
153
 * Make additional room in "buffer" for at least BUFFER_SIZE more
179
154
 * bytes. "buffer_capacity" is how much is currently allocated,
191
166
  return buffer_capacity;
192
167
}
193
168
 
194
 
/* 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){
198
 
  int ret;
199
 
  server *new_server = malloc(sizeof(server));
200
 
  if(new_server == NULL){
201
 
    perror_plus("malloc");
202
 
    return -1;
203
 
  }
204
 
  *new_server = (server){ .ip = strdup(ip),
205
 
                         .port = port,
206
 
                         .if_index = if_index,
207
 
                         .af = af };
208
 
  if(new_server->ip == NULL){
209
 
    perror_plus("strdup");
210
 
    return -1;
211
 
  }
212
 
  /* Special case of first server */
213
 
  if (mc.current_server == NULL){
214
 
    new_server->next = new_server;
215
 
    new_server->prev = new_server;
216
 
    mc.current_server = new_server;
217
 
  /* Place the new server last in the list */
218
 
  } else {
219
 
    new_server->next = mc.current_server;
220
 
    new_server->prev = mc.current_server->prev;
221
 
    new_server->prev->next = new_server;
222
 
    mc.current_server->prev = new_server;
223
 
  }
224
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
225
 
  if(ret == -1){
226
 
    perror_plus("clock_gettime");
227
 
    return -1;
228
 
  }
229
 
  return 0;
230
 
}
231
 
 
232
169
/* 
233
170
 * Initialize GPGME.
234
171
 */
248
185
    
249
186
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
250
187
    if(fd == -1){
251
 
      perror_plus("open");
 
188
      perror("open");
252
189
      return false;
253
190
    }
254
191
    
255
192
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
256
193
    if(rc != GPG_ERR_NO_ERROR){
257
 
      fprintf(stderr, "Mandos plugin mandos-client: "
258
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
194
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
259
195
              gpgme_strsource(rc), gpgme_strerror(rc));
260
196
      return false;
261
197
    }
262
198
    
263
199
    rc = gpgme_op_import(mc.ctx, pgp_data);
264
200
    if(rc != GPG_ERR_NO_ERROR){
265
 
      fprintf(stderr, "Mandos plugin mandos-client: "
266
 
              "bad gpgme_op_import: %s: %s\n",
 
201
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
267
202
              gpgme_strsource(rc), gpgme_strerror(rc));
268
203
      return false;
269
204
    }
270
205
    
271
206
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
272
207
    if(ret == -1){
273
 
      perror_plus("close");
 
208
      perror("close");
274
209
    }
275
210
    gpgme_data_release(pgp_data);
276
211
    return true;
277
212
  }
278
213
  
279
214
  if(debug){
280
 
    fprintf(stderr, "Mandos plugin mandos-client: "
281
 
            "Initializing GPGME\n");
 
215
    fprintf(stderr, "Initializing GPGME\n");
282
216
  }
283
217
  
284
218
  /* Init GPGME */
285
219
  gpgme_check_version(NULL);
286
220
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
287
221
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "Mandos plugin mandos-client: "
289
 
            "bad gpgme_engine_check_version: %s: %s\n",
 
222
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
290
223
            gpgme_strsource(rc), gpgme_strerror(rc));
291
224
    return false;
292
225
  }
293
226
  
294
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
227
    /* Set GPGME home directory for the OpenPGP engine only */
295
228
  rc = gpgme_get_engine_info(&engine_info);
296
229
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf(stderr, "Mandos plugin mandos-client: "
298
 
            "bad gpgme_get_engine_info: %s: %s\n",
 
230
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
299
231
            gpgme_strsource(rc), gpgme_strerror(rc));
300
232
    return false;
301
233
  }
308
240
    engine_info = engine_info->next;
309
241
  }
310
242
  if(engine_info == NULL){
311
 
    fprintf(stderr, "Mandos plugin mandos-client: "
312
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
243
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
313
244
    return false;
314
245
  }
315
246
  
316
247
  /* Create new GPGME "context" */
317
248
  rc = gpgme_new(&(mc.ctx));
318
249
  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));
 
250
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
251
            gpgme_strsource(rc), gpgme_strerror(rc));
322
252
    return false;
323
253
  }
324
254
  
343
273
  ssize_t plaintext_length = 0;
344
274
  
345
275
  if(debug){
346
 
    fprintf(stderr, "Mandos plugin mandos-client: "
347
 
            "Trying to decrypt OpenPGP data\n");
 
276
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
348
277
  }
349
278
  
350
279
  /* Create new GPGME data buffer from memory cryptotext */
351
280
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
352
281
                               0);
353
282
  if(rc != GPG_ERR_NO_ERROR){
354
 
    fprintf(stderr, "Mandos plugin mandos-client: "
355
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
283
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
356
284
            gpgme_strsource(rc), gpgme_strerror(rc));
357
285
    return -1;
358
286
  }
360
288
  /* Create new empty GPGME data buffer for the plaintext */
361
289
  rc = gpgme_data_new(&dh_plain);
362
290
  if(rc != GPG_ERR_NO_ERROR){
363
 
    fprintf(stderr, "Mandos plugin mandos-client: "
364
 
            "bad gpgme_data_new: %s: %s\n",
 
291
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
365
292
            gpgme_strsource(rc), gpgme_strerror(rc));
366
293
    gpgme_data_release(dh_crypto);
367
294
    return -1;
371
298
     data buffer */
372
299
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
373
300
  if(rc != GPG_ERR_NO_ERROR){
374
 
    fprintf(stderr, "Mandos plugin mandos-client: "
375
 
            "bad gpgme_op_decrypt: %s: %s\n",
 
301
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
376
302
            gpgme_strsource(rc), gpgme_strerror(rc));
377
303
    plaintext_length = -1;
378
304
    if(debug){
379
305
      gpgme_decrypt_result_t result;
380
306
      result = gpgme_op_decrypt_result(mc.ctx);
381
307
      if(result == NULL){
382
 
        fprintf(stderr, "Mandos plugin mandos-client: "
383
 
                "gpgme_op_decrypt_result failed\n");
 
308
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
384
309
      } else {
385
 
        fprintf(stderr, "Mandos plugin mandos-client: "
386
 
                "Unsupported algorithm: %s\n",
 
310
        fprintf(stderr, "Unsupported algorithm: %s\n",
387
311
                result->unsupported_algorithm);
388
 
        fprintf(stderr, "Mandos plugin mandos-client: "
389
 
                "Wrong key usage: %u\n",
 
312
        fprintf(stderr, "Wrong key usage: %u\n",
390
313
                result->wrong_key_usage);
391
314
        if(result->file_name != NULL){
392
 
          fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                  "File name: %s\n", result->file_name);
 
315
          fprintf(stderr, "File name: %s\n", result->file_name);
394
316
        }
395
317
        gpgme_recipient_t recipient;
396
318
        recipient = result->recipients;
397
319
        while(recipient != NULL){
398
 
          fprintf(stderr, "Mandos plugin mandos-client: "
399
 
                  "Public key algorithm: %s\n",
 
320
          fprintf(stderr, "Public key algorithm: %s\n",
400
321
                  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",
 
322
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
323
          fprintf(stderr, "Secret key available: %s\n",
405
324
                  recipient->status == GPG_ERR_NO_SECKEY
406
325
                  ? "No" : "Yes");
407
326
          recipient = recipient->next;
412
331
  }
413
332
  
414
333
  if(debug){
415
 
    fprintf(stderr, "Mandos plugin mandos-client: "
416
 
            "Decryption of OpenPGP data succeeded\n");
 
334
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
417
335
  }
418
336
  
419
337
  /* Seek back to the beginning of the GPGME plaintext data buffer */
420
338
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
421
 
    perror_plus("gpgme_data_seek");
 
339
    perror("gpgme_data_seek");
422
340
    plaintext_length = -1;
423
341
    goto decrypt_end;
424
342
  }
429
347
                                      (size_t)plaintext_length,
430
348
                                      plaintext_capacity);
431
349
    if(plaintext_capacity == 0){
432
 
        perror_plus("incbuffer");
 
350
        perror("incbuffer");
433
351
        plaintext_length = -1;
434
352
        goto decrypt_end;
435
353
    }
442
360
      break;
443
361
    }
444
362
    if(ret < 0){
445
 
      perror_plus("gpgme_data_read");
 
363
      perror("gpgme_data_read");
446
364
      plaintext_length = -1;
447
365
      goto decrypt_end;
448
366
    }
450
368
  }
451
369
  
452
370
  if(debug){
453
 
    fprintf(stderr, "Mandos plugin mandos-client: "
454
 
            "Decrypted password is: ");
 
371
    fprintf(stderr, "Decrypted password is: ");
455
372
    for(ssize_t i = 0; i < plaintext_length; i++){
456
373
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
457
374
    }
479
396
/* GnuTLS log function callback */
480
397
static void debuggnutls(__attribute__((unused)) int level,
481
398
                        const char* string){
482
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
399
  fprintf(stderr, "GnuTLS: %s", string);
483
400
}
484
401
 
485
402
static int init_gnutls_global(const char *pubkeyfilename,
487
404
  int ret;
488
405
  
489
406
  if(debug){
490
 
    fprintf(stderr, "Mandos plugin mandos-client: "
491
 
            "Initializing GnuTLS\n");
 
407
    fprintf(stderr, "Initializing GnuTLS\n");
492
408
  }
493
409
  
494
410
  ret = gnutls_global_init();
495
411
  if(ret != GNUTLS_E_SUCCESS){
496
 
    fprintf(stderr, "Mandos plugin mandos-client: "
497
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
412
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
413
            safer_gnutls_strerror(ret));
498
414
    return -1;
499
415
  }
500
416
  
507
423
  }
508
424
  
509
425
  /* OpenPGP credentials */
510
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
426
  gnutls_certificate_allocate_credentials(&mc.cred);
511
427
  if(ret != GNUTLS_E_SUCCESS){
512
 
    fprintf(stderr, "Mandos plugin mandos-client: "
513
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
428
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
429
                                                    from
 
430
                                                    -Wunreachable-code
 
431
                                                 */
 
432
            safer_gnutls_strerror(ret));
514
433
    gnutls_global_deinit();
515
434
    return -1;
516
435
  }
517
436
  
518
437
  if(debug){
519
 
    fprintf(stderr, "Mandos plugin mandos-client: "
520
 
            "Attempting to use OpenPGP public key %s and"
 
438
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
521
439
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
522
440
            seckeyfilename);
523
441
  }
527
445
     GNUTLS_OPENPGP_FMT_BASE64);
528
446
  if(ret != GNUTLS_E_SUCCESS){
529
447
    fprintf(stderr,
530
 
            "Mandos plugin mandos-client: "
531
448
            "Error[%d] while reading the OpenPGP key pair ('%s',"
532
449
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
533
 
    fprintf(stderr, "Mandos plugin mandos-client: "
534
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
450
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
451
            safer_gnutls_strerror(ret));
535
452
    goto globalfail;
536
453
  }
537
454
  
538
455
  /* GnuTLS server initialization */
539
456
  ret = gnutls_dh_params_init(&mc.dh_params);
540
457
  if(ret != GNUTLS_E_SUCCESS){
541
 
    fprintf(stderr, "Mandos plugin mandos-client: "
542
 
            "Error in GnuTLS DH parameter initialization:"
 
458
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
543
459
            " %s\n", safer_gnutls_strerror(ret));
544
460
    goto globalfail;
545
461
  }
546
462
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
547
463
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Mandos plugin mandos-client: "
549
 
            "Error in GnuTLS prime generation: %s\n",
 
464
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
550
465
            safer_gnutls_strerror(ret));
551
466
    goto globalfail;
552
467
  }
573
488
    }
574
489
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
575
490
  if(ret != GNUTLS_E_SUCCESS){
576
 
    fprintf(stderr, "Mandos plugin mandos-client: "
577
 
            "Error in GnuTLS session initialization: %s\n",
 
491
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
578
492
            safer_gnutls_strerror(ret));
579
493
  }
580
494
  
588
502
      }
589
503
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
590
504
    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));
 
505
      fprintf(stderr, "Syntax error at: %s\n", err);
 
506
      fprintf(stderr, "GnuTLS error: %s\n",
 
507
              safer_gnutls_strerror(ret));
595
508
      gnutls_deinit(*session);
596
509
      return -1;
597
510
    }
606
519
    }
607
520
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
608
521
  if(ret != GNUTLS_E_SUCCESS){
609
 
    fprintf(stderr, "Mandos plugin mandos-client: "
610
 
            "Error setting GnuTLS credentials: %s\n",
 
522
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
611
523
            safer_gnutls_strerror(ret));
612
524
    gnutls_deinit(*session);
613
525
    return -1;
659
571
    pf = PF_INET;
660
572
    break;
661
573
  default:
662
 
    fprintf(stderr, "Mandos plugin mandos-client: "
663
 
            "Bad address family: %d\n", af);
 
574
    fprintf(stderr, "Bad address family: %d\n", af);
664
575
    errno = EINVAL;
665
576
    return -1;
666
577
  }
671
582
  }
672
583
  
673
584
  if(debug){
674
 
    fprintf(stderr, "Mandos plugin mandos-client: "
675
 
            "Setting up a TCP connection to %s, port %" PRIu16
 
585
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
676
586
            "\n", ip, port);
677
587
  }
678
588
  
679
589
  tcp_sd = socket(pf, SOCK_STREAM, 0);
680
590
  if(tcp_sd < 0){
681
591
    int e = errno;
682
 
    perror_plus("socket");
 
592
    perror("socket");
683
593
    errno = e;
684
594
    goto mandos_end;
685
595
  }
699
609
  }
700
610
  if(ret < 0 ){
701
611
    int e = errno;
702
 
    perror_plus("inet_pton");
 
612
    perror("inet_pton");
703
613
    errno = e;
704
614
    goto mandos_end;
705
615
  }
706
616
  if(ret == 0){
707
617
    int e = errno;
708
 
    fprintf(stderr, "Mandos plugin mandos-client: "
709
 
            "Bad address: %s\n", ip);
 
618
    fprintf(stderr, "Bad address: %s\n", ip);
710
619
    errno = e;
711
620
    goto mandos_end;
712
621
  }
719
628
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
720
629
                              -Wunreachable-code*/
721
630
      if(if_index == AVAHI_IF_UNSPEC){
722
 
        fprintf(stderr, "Mandos plugin mandos-client: "
723
 
                "An IPv6 link-local address is incomplete"
 
631
        fprintf(stderr, "An IPv6 link-local address is incomplete"
724
632
                " without a network interface\n");
725
633
        errno = EINVAL;
726
634
        goto mandos_end;
743
651
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
744
652
      char interface[IF_NAMESIZE];
745
653
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
746
 
        perror_plus("if_indextoname");
 
654
        perror("if_indextoname");
747
655
      } else {
748
 
        fprintf(stderr, "Mandos plugin mandos-client: "
749
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
656
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
750
657
                ip, interface, port);
751
658
      }
752
659
    } else {
753
 
      fprintf(stderr, "Mandos plugin mandos-client: "
754
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
660
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
661
              port);
755
662
    }
756
663
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
757
664
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
764
671
                        sizeof(addrstr));
765
672
    }
766
673
    if(pcret == NULL){
767
 
      perror_plus("inet_ntop");
 
674
      perror("inet_ntop");
768
675
    } else {
769
676
      if(strcmp(addrstr, ip) != 0){
770
 
        fprintf(stderr, "Mandos plugin mandos-client: "
771
 
                "Canonical address form: %s\n", addrstr);
 
677
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
772
678
      }
773
679
    }
774
680
  }
786
692
  if(ret < 0){
787
693
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
788
694
      int e = errno;
789
 
      perror_plus("connect");
 
695
      perror("connect");
790
696
      errno = e;
791
697
    }
792
698
    goto mandos_end;
805
711
                                   out_size - written));
806
712
    if(ret == -1){
807
713
      int e = errno;
808
 
      perror_plus("write");
 
714
      perror("write");
809
715
      errno = e;
810
716
      goto mandos_end;
811
717
    }
828
734
  }
829
735
  
830
736
  if(debug){
831
 
    fprintf(stderr, "Mandos plugin mandos-client: "
832
 
            "Establishing TLS session with %s\n", ip);
 
737
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
833
738
  }
834
739
  
835
740
  if(quit_now){
837
742
    goto mandos_end;
838
743
  }
839
744
  
840
 
  /* Spurious warning from -Wint-to-pointer-cast */
841
745
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
842
746
  
843
747
  if(quit_now){
855
759
  
856
760
  if(ret != GNUTLS_E_SUCCESS){
857
761
    if(debug){
858
 
      fprintf(stderr, "Mandos plugin mandos-client: "
859
 
              "*** GnuTLS Handshake failed ***\n");
 
762
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
860
763
      gnutls_perror(ret);
861
764
    }
862
765
    errno = EPROTO;
866
769
  /* Read OpenPGP packet that contains the wanted password */
867
770
  
868
771
  if(debug){
869
 
    fprintf(stderr, "Mandos plugin mandos-client: "
870
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
772
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
773
            ip);
871
774
  }
872
775
  
873
776
  while(true){
881
784
                                   buffer_capacity);
882
785
    if(buffer_capacity == 0){
883
786
      int e = errno;
884
 
      perror_plus("incbuffer");
 
787
      perror("incbuffer");
885
788
      errno = e;
886
789
      goto mandos_end;
887
790
    }
911
814
          }
912
815
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
913
816
        if(ret < 0){
914
 
          fprintf(stderr, "Mandos plugin mandos-client: "
915
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
817
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
916
818
          gnutls_perror(ret);
917
819
          errno = EPROTO;
918
820
          goto mandos_end;
919
821
        }
920
822
        break;
921
823
      default:
922
 
        fprintf(stderr, "Mandos plugin mandos-client: "
923
 
                "Unknown error while reading data from"
 
824
        fprintf(stderr, "Unknown error while reading data from"
924
825
                " encrypted session with Mandos server\n");
925
826
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
926
827
        errno = EIO;
932
833
  }
933
834
  
934
835
  if(debug){
935
 
    fprintf(stderr, "Mandos plugin mandos-client: "
936
 
            "Closing TLS session\n");
 
836
    fprintf(stderr, "Closing TLS session\n");
937
837
  }
938
838
  
939
839
  if(quit_now){
969
869
        if(ret == 0 and ferror(stdout)){
970
870
          int e = errno;
971
871
          if(debug){
972
 
            fprintf(stderr, "Mandos plugin mandos-client: "
973
 
                    "Error writing encrypted data: %s\n",
 
872
            fprintf(stderr, "Error writing encrypted data: %s\n",
974
873
                    strerror(errno));
975
874
          }
976
875
          errno = e;
996
895
      if(e == 0){
997
896
        e = errno;
998
897
      }
999
 
      perror_plus("close");
 
898
      perror("close");
1000
899
    }
1001
900
    gnutls_deinit(session);
1002
 
    errno = e;
1003
901
    if(quit_now){
1004
 
      errno = EINTR;
 
902
      e = EINTR;
1005
903
      retval = -1;
1006
904
    }
 
905
    errno = e;
1007
906
  }
1008
907
  return retval;
1009
908
}
1034
933
  switch(event){
1035
934
  default:
1036
935
  case AVAHI_RESOLVER_FAILURE:
1037
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1038
 
            "(Avahi Resolver) Failed to resolve service '%s'"
 
936
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
1039
937
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1040
938
            avahi_strerror(avahi_server_errno(mc.server)));
1041
939
    break;
1045
943
      char ip[AVAHI_ADDRESS_STR_MAX];
1046
944
      avahi_address_snprint(ip, sizeof(ip), address);
1047
945
      if(debug){
1048
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1049
 
                "Mandos server \"%s\" found on %s (%s, %"
 
946
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1050
947
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1051
948
                ip, (intmax_t)interface, port);
1052
949
      }
1054
951
                                           avahi_proto_to_af(proto));
1055
952
      if(ret == 0){
1056
953
        avahi_simple_poll_quit(mc.simple_poll);
1057
 
      } else {
1058
 
        ret = add_server(ip, port, interface,
1059
 
                         avahi_proto_to_af(proto));
1060
954
      }
1061
955
    }
1062
956
  }
1086
980
  default:
1087
981
  case AVAHI_BROWSER_FAILURE:
1088
982
    
1089
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1090
 
            "(Avahi browser) %s\n",
 
983
    fprintf(stderr, "(Avahi browser) %s\n",
1091
984
            avahi_strerror(avahi_server_errno(mc.server)));
1092
985
    avahi_simple_poll_quit(mc.simple_poll);
1093
986
    return;
1101
994
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1102
995
                                    name, type, domain, protocol, 0,
1103
996
                                    resolve_callback, NULL) == NULL)
1104
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1105
 
              "Avahi: Failed to resolve service '%s': %s\n",
 
997
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1106
998
              name, avahi_strerror(avahi_server_errno(mc.server)));
1107
999
    break;
1108
1000
    
1112
1004
  case AVAHI_BROWSER_ALL_FOR_NOW:
1113
1005
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1114
1006
    if(debug){
1115
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1116
 
              "No Mandos server found, still searching...\n");
 
1007
      fprintf(stderr, "No Mandos server found, still searching...\n");
1117
1008
    }
1118
1009
    break;
1119
1010
  }
1120
1011
}
1121
1012
 
1122
 
/* Signal handler that stops main loop after SIGTERM */
 
1013
/* stop main loop after sigterm has been called */
1123
1014
static void handle_sigterm(int sig){
1124
1015
  if(quit_now){
1125
1016
    return;
1127
1018
  quit_now = 1;
1128
1019
  signal_received = sig;
1129
1020
  int old_errno = errno;
1130
 
  /* set main loop to exit */
1131
1021
  if(mc.simple_poll != NULL){
1132
1022
    avahi_simple_poll_quit(mc.simple_poll);
1133
1023
  }
1134
1024
  errno = old_errno;
1135
1025
}
1136
1026
 
1137
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1138
 
  int ret;
1139
 
  
1140
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1141
 
  if(s < 0){
1142
 
    perror_plus("socket");
1143
 
    return false;
1144
 
  }
1145
 
  strcpy(ifr->ifr_name, ifname);
1146
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1147
 
  if(ret == -1){
 
1027
/* 
 
1028
 * This function determines if a directory entry in /sys/class/net
 
1029
 * corresponds to an acceptable network device.
 
1030
 * (This function is passed to scandir(3) as a filter function.)
 
1031
 */
 
1032
int good_interface(const struct dirent *if_entry){
 
1033
  ssize_t ssret;
 
1034
  char *flagname = NULL;
 
1035
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1036
                     if_entry->d_name);
 
1037
  if(ret < 0){
 
1038
    perror("asprintf");
 
1039
    return 0;
 
1040
  }
 
1041
  if(if_entry->d_name[0] == '.'){
 
1042
    return 0;
 
1043
  }
 
1044
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1045
  if(flags_fd == -1){
 
1046
    perror("open");
 
1047
    return 0;
 
1048
  }
 
1049
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1050
  /* read line from flags_fd */
 
1051
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1052
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1053
  flagstring[(size_t)to_read] = '\0';
 
1054
  if(flagstring == NULL){
 
1055
    perror("malloc");
 
1056
    close(flags_fd);
 
1057
    return 0;
 
1058
  }
 
1059
  while(to_read > 0){
 
1060
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1061
                                             (size_t)to_read));
 
1062
    if(ssret == -1){
 
1063
      perror("read");
 
1064
      free(flagstring);
 
1065
      close(flags_fd);
 
1066
      return 0;
 
1067
    }
 
1068
    to_read -= ssret;
 
1069
    if(ssret == 0){
 
1070
      break;
 
1071
    }
 
1072
  }
 
1073
  close(flags_fd);
 
1074
  intmax_t tmpmax;
 
1075
  char *tmp;
 
1076
  errno = 0;
 
1077
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1078
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1079
                                         and not (isspace(*tmp)))
 
1080
     or tmpmax != (ifreq_flags)tmpmax){
1148
1081
    if(debug){
1149
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1082
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1083
              flagstring, if_entry->d_name);
1150
1084
    }
1151
 
    return false;
 
1085
    free(flagstring);
 
1086
    return 0;
1152
1087
  }
1153
 
  return true;
1154
 
}
1155
 
 
1156
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1157
 
  
 
1088
  free(flagstring);
 
1089
  ifreq_flags flags = (ifreq_flags)tmpmax;
1158
1090
  /* Reject the loopback device */
1159
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1091
  if(flags & IFF_LOOPBACK){
1160
1092
    if(debug){
1161
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1162
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1093
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1094
              if_entry->d_name);
1163
1095
    }
1164
 
    return false;
 
1096
    return 0;
1165
1097
  }
1166
1098
  /* Accept point-to-point devices only if connect_to is specified */
1167
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1099
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1168
1100
    if(debug){
1169
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1170
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1101
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1102
              if_entry->d_name);
1171
1103
    }
1172
 
    return true;
 
1104
    return 1;
1173
1105
  }
1174
1106
  /* Otherwise, reject non-broadcast-capable devices */
1175
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1176
 
    if(debug){
1177
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1178
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
1179
 
    }
1180
 
    return false;
1181
 
  }
1182
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1183
 
  if(ifr->ifr_flags & IFF_NOARP){
1184
 
    if(debug){
1185
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1186
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
1187
 
    }
1188
 
    return false;
1189
 
  }
1190
 
  
 
1107
  if(not (flags & IFF_BROADCAST)){
 
1108
    if(debug){
 
1109
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1110
              if_entry->d_name);
 
1111
    }
 
1112
    return 0;
 
1113
  }
1191
1114
  /* Accept this device */
1192
1115
  if(debug){
1193
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1194
 
            "Interface \"%s\" is good\n", ifname);
1195
 
  }
1196
 
  return true;
1197
 
}
1198
 
 
1199
 
/* 
1200
 
 * This function determines if a directory entry in /sys/class/net
1201
 
 * corresponds to an acceptable network device.
1202
 
 * (This function is passed to scandir(3) as a filter function.)
1203
 
 */
1204
 
int good_interface(const struct dirent *if_entry){
1205
 
  if(if_entry->d_name[0] == '.'){
1206
 
    return 0;
1207
 
  }
1208
 
  
1209
 
  struct ifreq ifr;
1210
 
  if(not get_flags(if_entry->d_name, &ifr)){
1211
 
    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;
1269
 
}
1270
 
 
1271
 
int notdotentries(const struct dirent *direntry){
1272
 
  /* Skip "." and ".." */
1273
 
  if(direntry->d_name[0] == '.'
1274
 
     and (direntry->d_name[1] == '\0'
1275
 
          or (direntry->d_name[1] == '.'
1276
 
              and direntry->d_name[2] == '\0'))){
1277
 
    return 0;
1278
 
  }
1279
 
  return 1;
1280
 
}
1281
 
 
1282
 
/* Is this directory entry a runnable program? */
1283
 
int runnable_hook(const struct dirent *direntry){
1284
 
  int ret;
1285
 
  struct stat st;
1286
 
  
1287
 
  if((direntry->d_name)[0] == '\0'){
1288
 
    /* Empty name? */
1289
 
    return 0;
1290
 
  }
1291
 
  
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 */
1307
 
  
1308
 
  char *fullname = NULL;
1309
 
  ret = asprintf(&fullname, "%s/%s", hookdir,
1310
 
                 direntry->d_name);
1311
 
  if(ret < 0){
1312
 
    perror_plus("asprintf");
1313
 
    return 0;
1314
 
  }
1315
 
  
1316
 
  ret = stat(fullname, &st);
1317
 
  if(ret == -1){
1318
 
    if(debug){
1319
 
      perror_plus("Could not stat plugin");
1320
 
    }
1321
 
    return 0;
1322
 
  }
1323
 
  if(not (S_ISREG(st.st_mode))){
1324
 
    /* Not a regular file */
1325
 
    return 0;
1326
 
  }
1327
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1328
 
    /* Not executable */
1329
 
    return 0;
1330
 
  }
1331
 
  return 1;
1332
 
}
1333
 
 
1334
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1335
 
  int ret;
1336
 
  struct timespec now;
1337
 
  struct timespec waited_time;
1338
 
  intmax_t block_time;
1339
 
  
1340
 
  while(true){
1341
 
    if(mc.current_server == NULL){
1342
 
      if (debug){
1343
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1344
 
                "Wait until first server is found. No timeout!\n");
1345
 
      }
1346
 
      ret = avahi_simple_poll_iterate(s, -1);
1347
 
    } else {
1348
 
      if (debug){
1349
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1350
 
                "Check current_server if we should run it,"
1351
 
                " or wait\n");
1352
 
      }
1353
 
      /* the current time */
1354
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1355
 
      if(ret == -1){
1356
 
        perror_plus("clock_gettime");
1357
 
        return -1;
1358
 
      }
1359
 
      /* Calculating in ms how long time between now and server
1360
 
         who we visted longest time ago. Now - last seen.  */
1361
 
      waited_time.tv_sec = (now.tv_sec
1362
 
                            - mc.current_server->last_seen.tv_sec);
1363
 
      waited_time.tv_nsec = (now.tv_nsec
1364
 
                             - mc.current_server->last_seen.tv_nsec);
1365
 
      /* total time is 10s/10,000ms.
1366
 
         Converting to s from ms by dividing by 1,000,
1367
 
         and ns to ms by dividing by 1,000,000. */
1368
 
      block_time = ((retry_interval
1369
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1370
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1371
 
      
1372
 
      if (debug){
1373
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1374
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
1375
 
      }
1376
 
      
1377
 
      if(block_time <= 0){
1378
 
        ret = start_mandos_communication(mc.current_server->ip,
1379
 
                                         mc.current_server->port,
1380
 
                                         mc.current_server->if_index,
1381
 
                                         mc.current_server->af);
1382
 
        if(ret == 0){
1383
 
          avahi_simple_poll_quit(mc.simple_poll);
1384
 
          return 0;
1385
 
        }
1386
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1387
 
                            &mc.current_server->last_seen);
1388
 
        if(ret == -1){
1389
 
          perror_plus("clock_gettime");
1390
 
          return -1;
1391
 
        }
1392
 
        mc.current_server = mc.current_server->next;
1393
 
        block_time = 0;         /* Call avahi to find new Mandos
1394
 
                                   servers, but don't block */
1395
 
      }
1396
 
      
1397
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1398
 
    }
1399
 
    if(ret != 0){
1400
 
      if (ret > 0 or errno != EINTR){
1401
 
        return (ret != 1) ? ret : 0;
1402
 
      }
1403
 
    }
1404
 
  }
 
1116
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1117
            if_entry->d_name);
 
1118
  }
 
1119
  return 1;
1405
1120
}
1406
1121
 
1407
1122
int main(int argc, char *argv[]){
1426
1141
  bool gnutls_initialized = false;
1427
1142
  bool gpgme_initialized = false;
1428
1143
  float delay = 2.5f;
1429
 
  double retry_interval = 10; /* 10s between trying a server and
1430
 
                                 retrying the same server again */
1431
1144
  
1432
1145
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1433
1146
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1439
1152
  errno = 0;
1440
1153
  ret = setgid(gid);
1441
1154
  if(ret == -1){
1442
 
    perror_plus("setgid");
 
1155
    perror("setgid");
1443
1156
  }
1444
1157
  
1445
1158
  /* Lower user privileges (temporarily) */
1446
1159
  errno = 0;
1447
1160
  ret = seteuid(uid);
1448
1161
  if(ret == -1){
1449
 
    perror_plus("seteuid");
 
1162
    perror("seteuid");
1450
1163
  }
1451
1164
  
1452
1165
  if(quit_now){
1487
1200
        .arg = "SECONDS",
1488
1201
        .doc = "Maximum delay to wait for interface startup",
1489
1202
        .group = 2 },
1490
 
      { .name = "retry", .key = 132,
1491
 
        .arg = "SECONDS",
1492
 
        .doc = "Retry interval used when denied by the mandos server",
1493
 
        .group = 2 },
1494
 
      { .name = "network-hook-dir", .key = 133,
1495
 
        .arg = "DIR",
1496
 
        .doc = "Directory where network hooks are located",
1497
 
        .group = 2 },
1498
1203
      /*
1499
1204
       * These reproduce what we would get without ARGP_NO_HELP
1500
1205
       */
1544
1249
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1545
1250
          argp_error(state, "Bad delay");
1546
1251
        }
1547
 
      case 132:                 /* --retry */
1548
 
        errno = 0;
1549
 
        retry_interval = strtod(arg, &tmp);
1550
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1551
 
           or (retry_interval * 1000) > INT_MAX
1552
 
           or retry_interval < 0){
1553
 
          argp_error(state, "Bad retry interval");
1554
 
        }
1555
 
        break;
1556
 
      case 133:                 /* --network-hook-dir */
1557
 
        hookdir = arg;
1558
1252
        break;
1559
1253
        /*
1560
1254
         * These reproduce what we would get without ARGP_NO_HELP
1567
1261
        argp_state_help(state, state->out_stream,
1568
1262
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1569
1263
      case 'V':                 /* --version */
1570
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1571
1264
        fprintf(state->out_stream, "%s\n", argp_program_version);
1572
1265
        exit(argp_err_exit_status);
1573
1266
        break;
1589
1282
    case ENOMEM:
1590
1283
    default:
1591
1284
      errno = ret;
1592
 
      perror_plus("argp_parse");
 
1285
      perror("argp_parse");
1593
1286
      exitcode = EX_OSERR;
1594
1287
      goto end;
1595
1288
    case EINVAL:
1597
1290
      goto end;
1598
1291
    }
1599
1292
  }
1600
 
    
1601
 
  {
1602
 
    /* Work around Debian bug #633582:
1603
 
       <http://bugs.debian.org/633582> */
1604
 
    struct stat st;
1605
 
    
1606
 
    /* 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);
1752
 
    }
1753
 
  }
1754
1293
  
1755
1294
  if(not debug){
1756
1295
    avahi_set_log_function(empty_log);
1757
1296
  }
1758
 
  
 
1297
 
1759
1298
  if(interface[0] == '\0'){
1760
1299
    struct dirent **direntries;
1761
 
    /* First look for interfaces that are up */
1762
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1300
    ret = scandir(sys_class_net, &direntries, good_interface,
1763
1301
                  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
1302
    if(ret >= 1){
1771
 
      /* Pick the first interface returned */
 
1303
      /* Pick the first good interface */
1772
1304
      interface = strdup(direntries[0]->d_name);
1773
1305
      if(debug){
1774
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1775
 
                "Using interface \"%s\"\n", interface);
 
1306
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1776
1307
      }
1777
1308
      if(interface == NULL){
1778
 
        perror_plus("malloc");
 
1309
        perror("malloc");
1779
1310
        free(direntries);
1780
1311
        exitcode = EXIT_FAILURE;
1781
1312
        goto end;
1783
1314
      free(direntries);
1784
1315
    } else {
1785
1316
      free(direntries);
1786
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1787
 
              "Could not find a network interface\n");
 
1317
      fprintf(stderr, "Could not find a network interface\n");
1788
1318
      exitcode = EXIT_FAILURE;
1789
1319
      goto end;
1790
1320
    }
1796
1326
  srand((unsigned int) time(NULL));
1797
1327
  mc.simple_poll = avahi_simple_poll_new();
1798
1328
  if(mc.simple_poll == NULL){
1799
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1800
 
            "Avahi: Failed to create simple poll object.\n");
 
1329
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1801
1330
    exitcode = EX_UNAVAILABLE;
1802
1331
    goto end;
1803
1332
  }
1805
1334
  sigemptyset(&sigterm_action.sa_mask);
1806
1335
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1807
1336
  if(ret == -1){
1808
 
    perror_plus("sigaddset");
 
1337
    perror("sigaddset");
1809
1338
    exitcode = EX_OSERR;
1810
1339
    goto end;
1811
1340
  }
1812
1341
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1813
1342
  if(ret == -1){
1814
 
    perror_plus("sigaddset");
 
1343
    perror("sigaddset");
1815
1344
    exitcode = EX_OSERR;
1816
1345
    goto end;
1817
1346
  }
1818
1347
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1819
1348
  if(ret == -1){
1820
 
    perror_plus("sigaddset");
 
1349
    perror("sigaddset");
1821
1350
    exitcode = EX_OSERR;
1822
1351
    goto end;
1823
1352
  }
1827
1356
  */
1828
1357
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1829
1358
  if(ret == -1){
1830
 
    perror_plus("sigaction");
 
1359
    perror("sigaction");
1831
1360
    return EX_OSERR;
1832
1361
  }
1833
1362
  if(old_sigterm_action.sa_handler != SIG_IGN){
1834
1363
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1835
1364
    if(ret == -1){
1836
 
      perror_plus("sigaction");
 
1365
      perror("sigaction");
1837
1366
      exitcode = EX_OSERR;
1838
1367
      goto end;
1839
1368
    }
1840
1369
  }
1841
1370
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1842
1371
  if(ret == -1){
1843
 
    perror_plus("sigaction");
 
1372
    perror("sigaction");
1844
1373
    return EX_OSERR;
1845
1374
  }
1846
1375
  if(old_sigterm_action.sa_handler != SIG_IGN){
1847
1376
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1848
1377
    if(ret == -1){
1849
 
      perror_plus("sigaction");
 
1378
      perror("sigaction");
1850
1379
      exitcode = EX_OSERR;
1851
1380
      goto end;
1852
1381
    }
1853
1382
  }
1854
1383
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1855
1384
  if(ret == -1){
1856
 
    perror_plus("sigaction");
 
1385
    perror("sigaction");
1857
1386
    return EX_OSERR;
1858
1387
  }
1859
1388
  if(old_sigterm_action.sa_handler != SIG_IGN){
1860
1389
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1861
1390
    if(ret == -1){
1862
 
      perror_plus("sigaction");
 
1391
      perror("sigaction");
1863
1392
      exitcode = EX_OSERR;
1864
1393
      goto end;
1865
1394
    }
1869
1398
  if(strcmp(interface, "none") != 0){
1870
1399
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1871
1400
    if(if_index == 0){
1872
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1873
 
              "No such interface: \"%s\"\n", interface);
 
1401
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1874
1402
      exitcode = EX_UNAVAILABLE;
1875
1403
      goto end;
1876
1404
    }
1883
1411
    errno = 0;
1884
1412
    ret = seteuid(0);
1885
1413
    if(ret == -1){
1886
 
      perror_plus("seteuid");
 
1414
      perror("seteuid");
1887
1415
    }
1888
1416
    
1889
1417
#ifdef __linux__
1893
1421
    bool restore_loglevel = true;
1894
1422
    if(ret == -1){
1895
1423
      restore_loglevel = false;
1896
 
      perror_plus("klogctl");
 
1424
      perror("klogctl");
1897
1425
    }
1898
1426
#endif  /* __linux__ */
1899
1427
    
1900
1428
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1901
1429
    if(sd < 0){
1902
 
      perror_plus("socket");
 
1430
      perror("socket");
1903
1431
      exitcode = EX_OSERR;
1904
1432
#ifdef __linux__
1905
1433
      if(restore_loglevel){
1906
1434
        ret = klogctl(7, NULL, 0);
1907
1435
        if(ret == -1){
1908
 
          perror_plus("klogctl");
 
1436
          perror("klogctl");
1909
1437
        }
1910
1438
      }
1911
1439
#endif  /* __linux__ */
1913
1441
      errno = 0;
1914
1442
      ret = seteuid(uid);
1915
1443
      if(ret == -1){
1916
 
        perror_plus("seteuid");
 
1444
        perror("seteuid");
1917
1445
      }
1918
1446
      goto end;
1919
1447
    }
1920
1448
    strcpy(network.ifr_name, interface);
1921
1449
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1922
1450
    if(ret == -1){
1923
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1451
      perror("ioctl SIOCGIFFLAGS");
1924
1452
#ifdef __linux__
1925
1453
      if(restore_loglevel){
1926
1454
        ret = klogctl(7, NULL, 0);
1927
1455
        if(ret == -1){
1928
 
          perror_plus("klogctl");
 
1456
          perror("klogctl");
1929
1457
        }
1930
1458
      }
1931
1459
#endif  /* __linux__ */
1934
1462
      errno = 0;
1935
1463
      ret = seteuid(uid);
1936
1464
      if(ret == -1){
1937
 
        perror_plus("seteuid");
 
1465
        perror("seteuid");
1938
1466
      }
1939
1467
      goto end;
1940
1468
    }
1944
1472
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1945
1473
      if(ret == -1){
1946
1474
        take_down_interface = false;
1947
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1475
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
1948
1476
        exitcode = EX_OSERR;
1949
1477
#ifdef __linux__
1950
1478
        if(restore_loglevel){
1951
1479
          ret = klogctl(7, NULL, 0);
1952
1480
          if(ret == -1){
1953
 
            perror_plus("klogctl");
 
1481
            perror("klogctl");
1954
1482
          }
1955
1483
        }
1956
1484
#endif  /* __linux__ */
1958
1486
        errno = 0;
1959
1487
        ret = seteuid(uid);
1960
1488
        if(ret == -1){
1961
 
          perror_plus("seteuid");
 
1489
          perror("seteuid");
1962
1490
        }
1963
1491
        goto end;
1964
1492
      }
1965
1493
    }
1966
 
    /* Sleep checking until interface is running.
1967
 
       Check every 0.25s, up to total time of delay */
 
1494
    /* sleep checking until interface is running */
1968
1495
    for(int i=0; i < delay * 4; i++){
1969
1496
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1970
1497
      if(ret == -1){
1971
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1498
        perror("ioctl SIOCGIFFLAGS");
1972
1499
      } else if(network.ifr_flags & IFF_RUNNING){
1973
1500
        break;
1974
1501
      }
1975
1502
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1976
1503
      ret = nanosleep(&sleeptime, NULL);
1977
1504
      if(ret == -1 and errno != EINTR){
1978
 
        perror_plus("nanosleep");
 
1505
        perror("nanosleep");
1979
1506
      }
1980
1507
    }
1981
1508
    if(not take_down_interface){
1982
1509
      /* We won't need the socket anymore */
1983
1510
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1984
1511
      if(ret == -1){
1985
 
        perror_plus("close");
 
1512
        perror("close");
1986
1513
      }
1987
1514
    }
1988
1515
#ifdef __linux__
1990
1517
      /* Restores kernel loglevel to default */
1991
1518
      ret = klogctl(7, NULL, 0);
1992
1519
      if(ret == -1){
1993
 
        perror_plus("klogctl");
 
1520
        perror("klogctl");
1994
1521
      }
1995
1522
    }
1996
1523
#endif  /* __linux__ */
2000
1527
      /* Lower privileges */
2001
1528
      ret = seteuid(uid);
2002
1529
      if(ret == -1){
2003
 
        perror_plus("seteuid");
 
1530
        perror("seteuid");
2004
1531
      }
2005
1532
    } else {
2006
1533
      /* Lower privileges permanently */
2007
1534
      ret = setuid(uid);
2008
1535
      if(ret == -1){
2009
 
        perror_plus("setuid");
 
1536
        perror("setuid");
2010
1537
      }
2011
1538
    }
2012
1539
  }
2017
1544
  
2018
1545
  ret = init_gnutls_global(pubkey, seckey);
2019
1546
  if(ret == -1){
2020
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2021
 
            "init_gnutls_global failed\n");
 
1547
    fprintf(stderr, "init_gnutls_global failed\n");
2022
1548
    exitcode = EX_UNAVAILABLE;
2023
1549
    goto end;
2024
1550
  } else {
2029
1555
    goto end;
2030
1556
  }
2031
1557
  
 
1558
  tempdir_created = true;
2032
1559
  if(mkdtemp(tempdir) == NULL){
2033
 
    perror_plus("mkdtemp");
 
1560
    tempdir_created = false;
 
1561
    perror("mkdtemp");
2034
1562
    goto end;
2035
1563
  }
2036
 
  tempdir_created = true;
2037
1564
  
2038
1565
  if(quit_now){
2039
1566
    goto end;
2040
1567
  }
2041
1568
  
2042
1569
  if(not init_gpgme(pubkey, seckey, tempdir)){
2043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2044
 
            "init_gpgme failed\n");
 
1570
    fprintf(stderr, "init_gpgme failed\n");
2045
1571
    exitcode = EX_UNAVAILABLE;
2046
1572
    goto end;
2047
1573
  } else {
2057
1583
    /* (Mainly meant for debugging) */
2058
1584
    char *address = strrchr(connect_to, ':');
2059
1585
    if(address == NULL){
2060
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2061
 
              "No colon in address\n");
 
1586
      fprintf(stderr, "No colon in address\n");
2062
1587
      exitcode = EX_USAGE;
2063
1588
      goto end;
2064
1589
    }
2072
1597
    tmpmax = strtoimax(address+1, &tmp, 10);
2073
1598
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2074
1599
       or tmpmax != (uint16_t)tmpmax){
2075
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2076
 
              "Bad port number\n");
 
1600
      fprintf(stderr, "Bad port number\n");
2077
1601
      exitcode = EX_USAGE;
2078
1602
      goto end;
2079
1603
    }
2084
1608
    
2085
1609
    port = (uint16_t)tmpmax;
2086
1610
    *address = '\0';
 
1611
    address = connect_to;
2087
1612
    /* Colon in address indicates IPv6 */
2088
1613
    int af;
2089
 
    if(strchr(connect_to, ':') != NULL){
 
1614
    if(strchr(address, ':') != NULL){
2090
1615
      af = AF_INET6;
2091
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2092
 
      if(connect_to[0] == '[' and address[-1] == ']')
2093
 
        {
2094
 
          connect_to++;
2095
 
          address[-1] = '\0';
2096
 
        }
2097
1616
    } else {
2098
1617
      af = AF_INET;
2099
1618
    }
2100
 
    address = connect_to;
2101
1619
    
2102
1620
    if(quit_now){
2103
1621
      goto end;
2104
1622
    }
2105
 
    
 
1623
 
2106
1624
    while(not quit_now){
2107
1625
      ret = start_mandos_communication(address, port, if_index, af);
2108
1626
      if(quit_now or ret == 0){
2109
1627
        break;
2110
1628
      }
2111
 
      if(debug){
2112
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2113
 
                "Retrying in %d seconds\n", (int)retry_interval);
2114
 
      }
2115
 
      sleep((int)retry_interval);
2116
 
    }
2117
 
    
 
1629
      sleep(15);
 
1630
    };
 
1631
 
2118
1632
    if (not quit_now){
2119
1633
      exitcode = EXIT_SUCCESS;
2120
1634
    }
2121
 
    
 
1635
 
2122
1636
    goto end;
2123
1637
  }
2124
1638
  
2146
1660
  
2147
1661
  /* Check if creating the Avahi server object succeeded */
2148
1662
  if(mc.server == NULL){
2149
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2150
 
            "Failed to create Avahi server: %s\n",
 
1663
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2151
1664
            avahi_strerror(error));
2152
1665
    exitcode = EX_UNAVAILABLE;
2153
1666
    goto end;
2162
1675
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2163
1676
                                   NULL, 0, browse_callback, NULL);
2164
1677
  if(sb == NULL){
2165
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2166
 
            "Failed to create service browser: %s\n",
 
1678
    fprintf(stderr, "Failed to create service browser: %s\n",
2167
1679
            avahi_strerror(avahi_server_errno(mc.server)));
2168
1680
    exitcode = EX_UNAVAILABLE;
2169
1681
    goto end;
2176
1688
  /* Run the main loop */
2177
1689
  
2178
1690
  if(debug){
2179
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2180
 
            "Starting Avahi loop search\n");
2181
 
  }
2182
 
 
2183
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2184
 
                                (int)(retry_interval * 1000));
2185
 
  if(debug){
2186
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2187
 
            "avahi_loop_with_timeout exited %s\n",
2188
 
            (ret == 0) ? "successfully" : "with error");
2189
 
  }
 
1691
    fprintf(stderr, "Starting Avahi loop search\n");
 
1692
  }
 
1693
  
 
1694
  avahi_simple_poll_loop(mc.simple_poll);
2190
1695
  
2191
1696
 end:
2192
1697
  
2193
1698
  if(debug){
2194
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2195
 
            "%s exiting\n", argv[0]);
 
1699
    fprintf(stderr, "%s exiting\n", argv[0]);
2196
1700
  }
2197
1701
  
2198
1702
  /* Cleanup things */
2214
1718
  if(gpgme_initialized){
2215
1719
    gpgme_release(mc.ctx);
2216
1720
  }
2217
 
 
2218
 
  /* Cleans up the circular linked list of Mandos servers the client
2219
 
     has seen */
2220
 
  if(mc.current_server != NULL){
2221
 
    mc.current_server->prev->next = NULL;
2222
 
    while(mc.current_server != NULL){
2223
 
      server *next = mc.current_server->next;
2224
 
      free(mc.current_server);
2225
 
      mc.current_server = next;
2226
 
    }
2227
 
  }
2228
 
  
2229
 
  /* XXX run network hooks "stop" here  */
2230
1721
  
2231
1722
  /* Take down the network interface */
2232
1723
  if(take_down_interface){
2234
1725
    errno = 0;
2235
1726
    ret = seteuid(0);
2236
1727
    if(ret == -1){
2237
 
      perror_plus("seteuid");
 
1728
      perror("seteuid");
2238
1729
    }
2239
1730
    if(geteuid() == 0){
2240
1731
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2241
1732
      if(ret == -1){
2242
 
        perror_plus("ioctl SIOCGIFFLAGS");
2243
 
      } else if(network.ifr_flags & IFF_UP){
 
1733
        perror("ioctl SIOCGIFFLAGS");
 
1734
      } else if(network.ifr_flags & IFF_UP) {
2244
1735
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2245
1736
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2246
1737
        if(ret == -1){
2247
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1738
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
2248
1739
        }
2249
1740
      }
2250
1741
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2251
1742
      if(ret == -1){
2252
 
        perror_plus("close");
 
1743
        perror("close");
2253
1744
      }
2254
1745
      /* Lower privileges permanently */
2255
1746
      errno = 0;
2256
1747
      ret = setuid(uid);
2257
1748
      if(ret == -1){
2258
 
        perror_plus("setuid");
 
1749
        perror("setuid");
2259
1750
      }
2260
1751
    }
2261
1752
  }
2262
1753
  
2263
 
  /* Removes the GPGME temp directory and all files inside */
 
1754
  /* Removes the temp directory used by GPGME */
2264
1755
  if(tempdir_created){
2265
 
    struct dirent **direntries = NULL;
2266
 
    struct dirent *direntry = NULL;
2267
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2268
 
                             alphasort);
2269
 
    if (numentries > 0){
2270
 
      for(int i = 0; i < numentries; i++){
2271
 
        direntry = direntries[i];
 
1756
    DIR *d;
 
1757
    struct dirent *direntry;
 
1758
    d = opendir(tempdir);
 
1759
    if(d == NULL){
 
1760
      if(errno != ENOENT){
 
1761
        perror("opendir");
 
1762
      }
 
1763
    } else {
 
1764
      while(true){
 
1765
        direntry = readdir(d);
 
1766
        if(direntry == NULL){
 
1767
          break;
 
1768
        }
 
1769
        /* Skip "." and ".." */
 
1770
        if(direntry->d_name[0] == '.'
 
1771
           and (direntry->d_name[1] == '\0'
 
1772
                or (direntry->d_name[1] == '.'
 
1773
                    and direntry->d_name[2] == '\0'))){
 
1774
          continue;
 
1775
        }
2272
1776
        char *fullname = NULL;
2273
1777
        ret = asprintf(&fullname, "%s/%s", tempdir,
2274
1778
                       direntry->d_name);
2275
1779
        if(ret < 0){
2276
 
          perror_plus("asprintf");
 
1780
          perror("asprintf");
2277
1781
          continue;
2278
1782
        }
2279
1783
        ret = remove(fullname);
2280
1784
        if(ret == -1){
2281
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2282
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
1785
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1786
                  strerror(errno));
2283
1787
        }
2284
1788
        free(fullname);
2285
1789
      }
2286
 
    }
2287
 
 
2288
 
    /* need to clean even if 0 because man page doesn't specify */
2289
 
    free(direntries);
2290
 
    if (numentries == -1){
2291
 
      perror_plus("scandir");
 
1790
      closedir(d);
2292
1791
    }
2293
1792
    ret = rmdir(tempdir);
2294
1793
    if(ret == -1 and errno != ENOENT){
2295
 
      perror_plus("rmdir");
 
1794
      perror("rmdir");
2296
1795
    }
2297
1796
  }
2298
1797
  
2303
1802
                                            &old_sigterm_action,
2304
1803
                                            NULL));
2305
1804
    if(ret == -1){
2306
 
      perror_plus("sigaction");
 
1805
      perror("sigaction");
2307
1806
    }
2308
1807
    do {
2309
1808
      ret = raise(signal_received);
2310
1809
    } while(ret != 0 and errno == EINTR);
2311
1810
    if(ret != 0){
2312
 
      perror_plus("raise");
 
1811
      perror("raise");
2313
1812
      abort();
2314
1813
    }
2315
1814
    TEMP_FAILURE_RETRY(pause());