/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

merge

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,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 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@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.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() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
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 */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
66
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
75
                                   getuid(), getgid(), seteuid(),
75
76
                                   setgid(), pause() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
77
78
#include <iso646.h>             /* not, or, and */
78
79
#include <argp.h>               /* struct argp_option, error_t, struct
79
80
                                   argp_state, struct argp,
84
85
                                   raise() */
85
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
87
90
 
88
91
#ifdef __linux__
89
92
#include <sys/klog.h>           /* klogctl() */
107
110
                                   init_gnutls_session(),
108
111
                                   GNUTLS_* */
109
112
#include <gnutls/openpgp.h>
110
 
                          /* gnutls_certificate_set_openpgp_key_file(),
111
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
113
                         /* gnutls_certificate_set_openpgp_key_file(),
 
114
                            GNUTLS_OPENPGP_FMT_BASE64 */
112
115
 
113
116
/* GPGME */
114
117
#include <gpgme.h>              /* All GPGME types, constants and
122
125
#define PATHDIR "/conf/conf.d/mandos"
123
126
#define SECKEY "seckey.txt"
124
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
125
129
 
126
130
bool debug = false;
127
131
static const char mandos_protocol_version[] = "1";
128
132
const char *argp_program_version = "mandos-client " VERSION;
129
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
130
134
static const char sys_class_net[] = "/sys/class/net";
131
135
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;
132
148
 
133
149
/* Used for passing in values through the Avahi callback functions */
134
150
typedef struct {
139
155
  gnutls_dh_params_t dh_params;
140
156
  const char *priority;
141
157
  gpgme_ctx_t ctx;
 
158
  server *current_server;
142
159
} mandos_context;
143
160
 
144
161
/* global context so signal handler can reach it*/
145
162
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
163
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
164
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
165
                      .current_server = NULL };
148
166
 
149
167
sig_atomic_t quit_now = 0;
150
168
int signal_received = 0;
151
169
 
 
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
int fprintf_plus(FILE *stream, const char *format, ...){
 
178
  va_list ap;
 
179
  va_start (ap, format);
 
180
  
 
181
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
182
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
183
}
 
184
 
152
185
/*
153
186
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
187
 * bytes. "buffer_capacity" is how much is currently allocated,
155
188
 * "buffer_length" is how much is already used.
156
189
 */
157
190
size_t incbuffer(char **buffer, size_t buffer_length,
158
 
                  size_t buffer_capacity){
 
191
                 size_t buffer_capacity){
159
192
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
160
193
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
161
194
    if(buffer == NULL){
166
199
  return buffer_capacity;
167
200
}
168
201
 
 
202
/* Add server to set of servers to retry periodically */
 
203
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
204
               int af){
 
205
  int ret;
 
206
  server *new_server = malloc(sizeof(server));
 
207
  if(new_server == NULL){
 
208
    perror_plus("malloc");
 
209
    return -1;
 
210
  }
 
211
  *new_server = (server){ .ip = strdup(ip),
 
212
                          .port = port,
 
213
                          .if_index = if_index,
 
214
                          .af = af };
 
215
  if(new_server->ip == NULL){
 
216
    perror_plus("strdup");
 
217
    return -1;
 
218
  }
 
219
  /* Special case of first server */
 
220
  if (mc.current_server == NULL){
 
221
    new_server->next = new_server;
 
222
    new_server->prev = new_server;
 
223
    mc.current_server = new_server;
 
224
  /* Place the new server last in the list */
 
225
  } else {
 
226
    new_server->next = mc.current_server;
 
227
    new_server->prev = mc.current_server->prev;
 
228
    new_server->prev->next = new_server;
 
229
    mc.current_server->prev = new_server;
 
230
  }
 
231
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
232
  if(ret == -1){
 
233
    perror_plus("clock_gettime");
 
234
    return -1;
 
235
  }
 
236
  return 0;
 
237
}
 
238
 
169
239
/* 
170
240
 * Initialize GPGME.
171
241
 */
172
 
static bool init_gpgme(const char *seckey,
173
 
                       const char *pubkey, const char *tempdir){
 
242
static bool init_gpgme(const char *seckey, const char *pubkey,
 
243
                       const char *tempdir){
174
244
  gpgme_error_t rc;
175
245
  gpgme_engine_info_t engine_info;
176
246
  
185
255
    
186
256
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
257
    if(fd == -1){
188
 
      perror("open");
 
258
      perror_plus("open");
189
259
      return false;
190
260
    }
191
261
    
192
262
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
193
263
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
265
              "bad gpgme_data_new_from_fd: %s: %s\n",
195
266
              gpgme_strsource(rc), gpgme_strerror(rc));
196
267
      return false;
197
268
    }
198
269
    
199
270
    rc = gpgme_op_import(mc.ctx, pgp_data);
200
271
    if(rc != GPG_ERR_NO_ERROR){
201
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
272
      fprintf(stderr, "Mandos plugin mandos-client: "
 
273
              "bad gpgme_op_import: %s: %s\n",
202
274
              gpgme_strsource(rc), gpgme_strerror(rc));
203
275
      return false;
204
276
    }
205
277
    
206
278
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
279
    if(ret == -1){
208
 
      perror("close");
 
280
      perror_plus("close");
209
281
    }
210
282
    gpgme_data_release(pgp_data);
211
283
    return true;
212
284
  }
213
285
  
214
286
  if(debug){
215
 
    fprintf(stderr, "Initializing GPGME\n");
 
287
    fprintf(stderr, "Mandos plugin mandos-client: "
 
288
            "Initializing GPGME\n");
216
289
  }
217
290
  
218
291
  /* Init GPGME */
219
292
  gpgme_check_version(NULL);
220
293
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
221
294
  if(rc != GPG_ERR_NO_ERROR){
222
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
295
    fprintf(stderr, "Mandos plugin mandos-client: "
 
296
            "bad gpgme_engine_check_version: %s: %s\n",
223
297
            gpgme_strsource(rc), gpgme_strerror(rc));
224
298
    return false;
225
299
  }
226
300
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
301
  /* Set GPGME home directory for the OpenPGP engine only */
228
302
  rc = gpgme_get_engine_info(&engine_info);
229
303
  if(rc != GPG_ERR_NO_ERROR){
230
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
304
    fprintf(stderr, "Mandos plugin mandos-client: "
 
305
            "bad gpgme_get_engine_info: %s: %s\n",
231
306
            gpgme_strsource(rc), gpgme_strerror(rc));
232
307
    return false;
233
308
  }
240
315
    engine_info = engine_info->next;
241
316
  }
242
317
  if(engine_info == NULL){
243
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "Could not set GPGME home dir to %s\n", tempdir);
244
320
    return false;
245
321
  }
246
322
  
247
323
  /* Create new GPGME "context" */
248
324
  rc = gpgme_new(&(mc.ctx));
249
325
  if(rc != GPG_ERR_NO_ERROR){
250
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
251
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
326
    fprintf(stderr, "Mandos plugin mandos-client: "
 
327
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
328
            gpgme_strerror(rc));
252
329
    return false;
253
330
  }
254
331
  
273
350
  ssize_t plaintext_length = 0;
274
351
  
275
352
  if(debug){
276
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
353
    fprintf(stderr, "Mandos plugin mandos-client: "
 
354
            "Trying to decrypt OpenPGP data\n");
277
355
  }
278
356
  
279
357
  /* Create new GPGME data buffer from memory cryptotext */
280
358
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
281
359
                               0);
282
360
  if(rc != GPG_ERR_NO_ERROR){
283
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
361
    fprintf(stderr, "Mandos plugin mandos-client: "
 
362
            "bad gpgme_data_new_from_mem: %s: %s\n",
284
363
            gpgme_strsource(rc), gpgme_strerror(rc));
285
364
    return -1;
286
365
  }
288
367
  /* Create new empty GPGME data buffer for the plaintext */
289
368
  rc = gpgme_data_new(&dh_plain);
290
369
  if(rc != GPG_ERR_NO_ERROR){
291
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
370
    fprintf(stderr, "Mandos plugin mandos-client: "
 
371
            "bad gpgme_data_new: %s: %s\n",
292
372
            gpgme_strsource(rc), gpgme_strerror(rc));
293
373
    gpgme_data_release(dh_crypto);
294
374
    return -1;
298
378
     data buffer */
299
379
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
300
380
  if(rc != GPG_ERR_NO_ERROR){
301
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
381
    fprintf(stderr, "Mandos plugin mandos-client: "
 
382
            "bad gpgme_op_decrypt: %s: %s\n",
302
383
            gpgme_strsource(rc), gpgme_strerror(rc));
303
384
    plaintext_length = -1;
304
385
    if(debug){
305
386
      gpgme_decrypt_result_t result;
306
387
      result = gpgme_op_decrypt_result(mc.ctx);
307
388
      if(result == NULL){
308
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
389
        fprintf(stderr, "Mandos plugin mandos-client: "
 
390
                "gpgme_op_decrypt_result failed\n");
309
391
      } else {
310
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
392
        fprintf(stderr, "Mandos plugin mandos-client: "
 
393
                "Unsupported algorithm: %s\n",
311
394
                result->unsupported_algorithm);
312
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
395
        fprintf(stderr, "Mandos plugin mandos-client: "
 
396
                "Wrong key usage: %u\n",
313
397
                result->wrong_key_usage);
314
398
        if(result->file_name != NULL){
315
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
399
          fprintf(stderr, "Mandos plugin mandos-client: "
 
400
                  "File name: %s\n", result->file_name);
316
401
        }
317
402
        gpgme_recipient_t recipient;
318
403
        recipient = result->recipients;
319
404
        while(recipient != NULL){
320
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
405
          fprintf(stderr, "Mandos plugin mandos-client: "
 
406
                  "Public key algorithm: %s\n",
321
407
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
322
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
323
 
          fprintf(stderr, "Secret key available: %s\n",
 
408
          fprintf(stderr, "Mandos plugin mandos-client: "
 
409
                  "Key ID: %s\n", recipient->keyid);
 
410
          fprintf(stderr, "Mandos plugin mandos-client: "
 
411
                  "Secret key available: %s\n",
324
412
                  recipient->status == GPG_ERR_NO_SECKEY
325
413
                  ? "No" : "Yes");
326
414
          recipient = recipient->next;
331
419
  }
332
420
  
333
421
  if(debug){
334
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
422
    fprintf(stderr, "Mandos plugin mandos-client: "
 
423
            "Decryption of OpenPGP data succeeded\n");
335
424
  }
336
425
  
337
426
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
427
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
 
428
    perror_plus("gpgme_data_seek");
340
429
    plaintext_length = -1;
341
430
    goto decrypt_end;
342
431
  }
344
433
  *plaintext = NULL;
345
434
  while(true){
346
435
    plaintext_capacity = incbuffer(plaintext,
347
 
                                      (size_t)plaintext_length,
348
 
                                      plaintext_capacity);
 
436
                                   (size_t)plaintext_length,
 
437
                                   plaintext_capacity);
349
438
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
351
 
        plaintext_length = -1;
352
 
        goto decrypt_end;
 
439
      perror_plus("incbuffer");
 
440
      plaintext_length = -1;
 
441
      goto decrypt_end;
353
442
    }
354
443
    
355
444
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
360
449
      break;
361
450
    }
362
451
    if(ret < 0){
363
 
      perror("gpgme_data_read");
 
452
      perror_plus("gpgme_data_read");
364
453
      plaintext_length = -1;
365
454
      goto decrypt_end;
366
455
    }
368
457
  }
369
458
  
370
459
  if(debug){
371
 
    fprintf(stderr, "Decrypted password is: ");
 
460
    fprintf(stderr, "Mandos plugin mandos-client: "
 
461
            "Decrypted password is: ");
372
462
    for(ssize_t i = 0; i < plaintext_length; i++){
373
463
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
374
464
    }
396
486
/* GnuTLS log function callback */
397
487
static void debuggnutls(__attribute__((unused)) int level,
398
488
                        const char* string){
399
 
  fprintf(stderr, "GnuTLS: %s", string);
 
489
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
400
490
}
401
491
 
402
492
static int init_gnutls_global(const char *pubkeyfilename,
404
494
  int ret;
405
495
  
406
496
  if(debug){
407
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
497
    fprintf(stderr, "Mandos plugin mandos-client: "
 
498
            "Initializing GnuTLS\n");
408
499
  }
409
500
  
410
501
  ret = gnutls_global_init();
411
502
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
413
 
            safer_gnutls_strerror(ret));
 
503
    fprintf(stderr, "Mandos plugin mandos-client: "
 
504
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
414
505
    return -1;
415
506
  }
416
507
  
423
514
  }
424
515
  
425
516
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
517
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
518
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
432
 
            safer_gnutls_strerror(ret));
 
519
    fprintf(stderr, "Mandos plugin mandos-client: "
 
520
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
433
521
    gnutls_global_deinit();
434
522
    return -1;
435
523
  }
436
524
  
437
525
  if(debug){
438
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
526
    fprintf(stderr, "Mandos plugin mandos-client: "
 
527
            "Attempting to use OpenPGP public key %s and"
439
528
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
440
529
            seckeyfilename);
441
530
  }
445
534
     GNUTLS_OPENPGP_FMT_BASE64);
446
535
  if(ret != GNUTLS_E_SUCCESS){
447
536
    fprintf(stderr,
 
537
            "Mandos plugin mandos-client: "
448
538
            "Error[%d] while reading the OpenPGP key pair ('%s',"
449
539
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
450
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
451
 
            safer_gnutls_strerror(ret));
 
540
    fprintf(stderr, "Mandos plugin mandos-client: "
 
541
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
452
542
    goto globalfail;
453
543
  }
454
544
  
455
545
  /* GnuTLS server initialization */
456
546
  ret = gnutls_dh_params_init(&mc.dh_params);
457
547
  if(ret != GNUTLS_E_SUCCESS){
458
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
548
    fprintf(stderr, "Mandos plugin mandos-client: "
 
549
            "Error in GnuTLS DH parameter initialization:"
459
550
            " %s\n", safer_gnutls_strerror(ret));
460
551
    goto globalfail;
461
552
  }
462
553
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
463
554
  if(ret != GNUTLS_E_SUCCESS){
464
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
555
    fprintf(stderr, "Mandos plugin mandos-client: "
 
556
            "Error in GnuTLS prime generation: %s\n",
465
557
            safer_gnutls_strerror(ret));
466
558
    goto globalfail;
467
559
  }
488
580
    }
489
581
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
490
582
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
583
    fprintf(stderr, "Mandos plugin mandos-client: "
 
584
            "Error in GnuTLS session initialization: %s\n",
492
585
            safer_gnutls_strerror(ret));
493
586
  }
494
587
  
502
595
      }
503
596
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
504
597
    if(ret != GNUTLS_E_SUCCESS){
505
 
      fprintf(stderr, "Syntax error at: %s\n", err);
506
 
      fprintf(stderr, "GnuTLS error: %s\n",
507
 
              safer_gnutls_strerror(ret));
 
598
      fprintf(stderr, "Mandos plugin mandos-client: "
 
599
              "Syntax error at: %s\n", err);
 
600
      fprintf(stderr, "Mandos plugin mandos-client: "
 
601
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
508
602
      gnutls_deinit(*session);
509
603
      return -1;
510
604
    }
519
613
    }
520
614
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
521
615
  if(ret != GNUTLS_E_SUCCESS){
522
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
616
    fprintf(stderr, "Mandos plugin mandos-client: "
 
617
            "Error setting GnuTLS credentials: %s\n",
523
618
            safer_gnutls_strerror(ret));
524
619
    gnutls_deinit(*session);
525
620
    return -1;
571
666
    pf = PF_INET;
572
667
    break;
573
668
  default:
574
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
669
    fprintf(stderr, "Mandos plugin mandos-client: "
 
670
            "Bad address family: %d\n", af);
575
671
    errno = EINVAL;
576
672
    return -1;
577
673
  }
582
678
  }
583
679
  
584
680
  if(debug){
585
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
681
    fprintf(stderr, "Mandos plugin mandos-client: "
 
682
            "Setting up a TCP connection to %s, port %" PRIu16
586
683
            "\n", ip, port);
587
684
  }
588
685
  
589
686
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
687
  if(tcp_sd < 0){
591
688
    int e = errno;
592
 
    perror("socket");
 
689
    perror_plus("socket");
593
690
    errno = e;
594
691
    goto mandos_end;
595
692
  }
609
706
  }
610
707
  if(ret < 0 ){
611
708
    int e = errno;
612
 
    perror("inet_pton");
 
709
    perror_plus("inet_pton");
613
710
    errno = e;
614
711
    goto mandos_end;
615
712
  }
616
713
  if(ret == 0){
617
714
    int e = errno;
618
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
715
    fprintf(stderr, "Mandos plugin mandos-client: "
 
716
            "Bad address: %s\n", ip);
619
717
    errno = e;
620
718
    goto mandos_end;
621
719
  }
626
724
    
627
725
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
628
726
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
629
 
                              -Wunreachable-code*/
 
727
                                -Wunreachable-code*/
630
728
      if(if_index == AVAHI_IF_UNSPEC){
631
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
729
        fprintf(stderr, "Mandos plugin mandos-client: "
 
730
                "An IPv6 link-local address is incomplete"
632
731
                " without a network interface\n");
633
732
        errno = EINVAL;
634
733
        goto mandos_end;
651
750
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
751
      char interface[IF_NAMESIZE];
653
752
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
 
753
        perror_plus("if_indextoname");
655
754
      } else {
656
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
755
        fprintf(stderr, "Mandos plugin mandos-client: "
 
756
                "Connection to: %s%%%s, port %" PRIu16 "\n",
657
757
                ip, interface, port);
658
758
      }
659
759
    } else {
660
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
661
 
              port);
 
760
      fprintf(stderr, "Mandos plugin mandos-client: "
 
761
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
662
762
    }
663
763
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
664
764
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
671
771
                        sizeof(addrstr));
672
772
    }
673
773
    if(pcret == NULL){
674
 
      perror("inet_ntop");
 
774
      perror_plus("inet_ntop");
675
775
    } else {
676
776
      if(strcmp(addrstr, ip) != 0){
677
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
777
        fprintf(stderr, "Mandos plugin mandos-client: "
 
778
                "Canonical address form: %s\n", addrstr);
678
779
      }
679
780
    }
680
781
  }
692
793
  if(ret < 0){
693
794
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
795
      int e = errno;
695
 
      perror("connect");
 
796
      perror_plus("connect");
696
797
      errno = e;
697
798
    }
698
799
    goto mandos_end;
708
809
  while(true){
709
810
    size_t out_size = strlen(out);
710
811
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
711
 
                                   out_size - written));
 
812
                                        out_size - written));
712
813
    if(ret == -1){
713
814
      int e = errno;
714
 
      perror("write");
 
815
      perror_plus("write");
715
816
      errno = e;
716
817
      goto mandos_end;
717
818
    }
734
835
  }
735
836
  
736
837
  if(debug){
737
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
838
    fprintf(stderr, "Mandos plugin mandos-client: "
 
839
            "Establishing TLS session with %s\n", ip);
738
840
  }
739
841
  
740
842
  if(quit_now){
742
844
    goto mandos_end;
743
845
  }
744
846
  
 
847
  /* Spurious warning from -Wint-to-pointer-cast */
745
848
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
849
  
747
850
  if(quit_now){
759
862
  
760
863
  if(ret != GNUTLS_E_SUCCESS){
761
864
    if(debug){
762
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
865
      fprintf(stderr, "Mandos plugin mandos-client: "
 
866
              "*** GnuTLS Handshake failed ***\n");
763
867
      gnutls_perror(ret);
764
868
    }
765
869
    errno = EPROTO;
769
873
  /* Read OpenPGP packet that contains the wanted password */
770
874
  
771
875
  if(debug){
772
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
773
 
            ip);
 
876
    fprintf(stderr, "Mandos plugin mandos-client: "
 
877
            "Retrieving OpenPGP encrypted password from %s\n", ip);
774
878
  }
775
879
  
776
880
  while(true){
781
885
    }
782
886
    
783
887
    buffer_capacity = incbuffer(&buffer, buffer_length,
784
 
                                   buffer_capacity);
 
888
                                buffer_capacity);
785
889
    if(buffer_capacity == 0){
786
890
      int e = errno;
787
 
      perror("incbuffer");
 
891
      perror_plus("incbuffer");
788
892
      errno = e;
789
893
      goto mandos_end;
790
894
    }
814
918
          }
815
919
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
816
920
        if(ret < 0){
817
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
921
          fprintf(stderr, "Mandos plugin mandos-client: "
 
922
                  "*** GnuTLS Re-handshake failed ***\n");
818
923
          gnutls_perror(ret);
819
924
          errno = EPROTO;
820
925
          goto mandos_end;
821
926
        }
822
927
        break;
823
928
      default:
824
 
        fprintf(stderr, "Unknown error while reading data from"
 
929
        fprintf(stderr, "Mandos plugin mandos-client: "
 
930
                "Unknown error while reading data from"
825
931
                " encrypted session with Mandos server\n");
826
932
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
827
933
        errno = EIO;
833
939
  }
834
940
  
835
941
  if(debug){
836
 
    fprintf(stderr, "Closing TLS session\n");
 
942
    fprintf(stderr, "Mandos plugin mandos-client: "
 
943
            "Closing TLS session\n");
837
944
  }
838
945
  
839
946
  if(quit_now){
851
958
  
852
959
  if(buffer_length > 0){
853
960
    ssize_t decrypted_buffer_size;
854
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
855
 
                                               buffer_length,
 
961
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
856
962
                                               &decrypted_buffer);
857
963
    if(decrypted_buffer_size >= 0){
858
964
      
869
975
        if(ret == 0 and ferror(stdout)){
870
976
          int e = errno;
871
977
          if(debug){
872
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
978
            fprintf(stderr, "Mandos plugin mandos-client: "
 
979
                    "Error writing encrypted data: %s\n",
873
980
                    strerror(errno));
874
981
          }
875
982
          errno = e;
895
1002
      if(e == 0){
896
1003
        e = errno;
897
1004
      }
898
 
      perror("close");
 
1005
      perror_plus("close");
899
1006
    }
900
1007
    gnutls_deinit(session);
 
1008
    errno = e;
901
1009
    if(quit_now){
902
 
      e = EINTR;
 
1010
      errno = EINTR;
903
1011
      retval = -1;
904
1012
    }
905
 
    errno = e;
906
1013
  }
907
1014
  return retval;
908
1015
}
933
1040
  switch(event){
934
1041
  default:
935
1042
  case AVAHI_RESOLVER_FAILURE:
936
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
1043
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1044
            "(Avahi Resolver) Failed to resolve service '%s'"
937
1045
            " of type '%s' in domain '%s': %s\n", name, type, domain,
938
1046
            avahi_strerror(avahi_server_errno(mc.server)));
939
1047
    break;
943
1051
      char ip[AVAHI_ADDRESS_STR_MAX];
944
1052
      avahi_address_snprint(ip, sizeof(ip), address);
945
1053
      if(debug){
946
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1054
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1055
                "Mandos server \"%s\" found on %s (%s, %"
947
1056
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
948
1057
                ip, (intmax_t)interface, port);
949
1058
      }
951
1060
                                           avahi_proto_to_af(proto));
952
1061
      if(ret == 0){
953
1062
        avahi_simple_poll_quit(mc.simple_poll);
 
1063
      } else {
 
1064
        ret = add_server(ip, port, interface,
 
1065
                         avahi_proto_to_af(proto));
954
1066
      }
955
1067
    }
956
1068
  }
980
1092
  default:
981
1093
  case AVAHI_BROWSER_FAILURE:
982
1094
    
983
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1095
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1096
            "(Avahi browser) %s\n",
984
1097
            avahi_strerror(avahi_server_errno(mc.server)));
985
1098
    avahi_simple_poll_quit(mc.simple_poll);
986
1099
    return;
994
1107
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
995
1108
                                    name, type, domain, protocol, 0,
996
1109
                                    resolve_callback, NULL) == NULL)
997
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1110
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1111
              "Avahi: Failed to resolve service '%s': %s\n",
998
1112
              name, avahi_strerror(avahi_server_errno(mc.server)));
999
1113
    break;
1000
1114
    
1004
1118
  case AVAHI_BROWSER_ALL_FOR_NOW:
1005
1119
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1006
1120
    if(debug){
1007
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1121
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1122
              "No Mandos server found, still searching...\n");
1008
1123
    }
1009
1124
    break;
1010
1125
  }
1011
1126
}
1012
1127
 
1013
 
/* stop main loop after sigterm has been called */
 
1128
/* Signal handler that stops main loop after SIGTERM */
1014
1129
static void handle_sigterm(int sig){
1015
1130
  if(quit_now){
1016
1131
    return;
1018
1133
  quit_now = 1;
1019
1134
  signal_received = sig;
1020
1135
  int old_errno = errno;
 
1136
  /* set main loop to exit */
1021
1137
  if(mc.simple_poll != NULL){
1022
1138
    avahi_simple_poll_quit(mc.simple_poll);
1023
1139
  }
1024
1140
  errno = old_errno;
1025
1141
}
1026
1142
 
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){
 
1143
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1144
  int ret;
 
1145
  
 
1146
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1147
  if(s < 0){
 
1148
    perror_plus("socket");
 
1149
    return false;
 
1150
  }
 
1151
  strcpy(ifr->ifr_name, ifname);
 
1152
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1153
  if(ret == -1){
1081
1154
    if(debug){
1082
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1083
 
              flagstring, if_entry->d_name);
 
1155
      perror_plus("ioctl SIOCGIFFLAGS");
1084
1156
    }
1085
 
    free(flagstring);
1086
 
    return 0;
 
1157
    return false;
1087
1158
  }
1088
 
  free(flagstring);
1089
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1159
  return true;
 
1160
}
 
1161
 
 
1162
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1163
  
1090
1164
  /* Reject the loopback device */
1091
 
  if(flags & IFF_LOOPBACK){
 
1165
  if(ifr->ifr_flags & IFF_LOOPBACK){
1092
1166
    if(debug){
1093
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1094
 
              if_entry->d_name);
 
1167
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1168
              "Rejecting loopback interface \"%s\"\n", ifname);
1095
1169
    }
1096
 
    return 0;
 
1170
    return false;
1097
1171
  }
1098
1172
  /* Accept point-to-point devices only if connect_to is specified */
1099
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1173
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1100
1174
    if(debug){
1101
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1102
 
              if_entry->d_name);
 
1175
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1176
              "Accepting point-to-point interface \"%s\"\n", ifname);
1103
1177
    }
1104
 
    return 1;
 
1178
    return true;
1105
1179
  }
1106
1180
  /* Otherwise, reject non-broadcast-capable devices */
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
 
  }
 
1181
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1182
    if(debug){
 
1183
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1184
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1185
    }
 
1186
    return false;
 
1187
  }
 
1188
  /* Reject non-ARP interfaces (including dummy interfaces) */
 
1189
  if(ifr->ifr_flags & IFF_NOARP){
 
1190
    if(debug){
 
1191
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1192
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1193
    }
 
1194
    return false;
 
1195
  }
 
1196
  
1114
1197
  /* Accept this device */
1115
1198
  if(debug){
1116
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1117
 
            if_entry->d_name);
1118
 
  }
1119
 
  return 1;
 
1199
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1200
            "Interface \"%s\" is good\n", ifname);
 
1201
  }
 
1202
  return true;
 
1203
}
 
1204
 
 
1205
/* 
 
1206
 * This function determines if a directory entry in /sys/class/net
 
1207
 * corresponds to an acceptable network device.
 
1208
 * (This function is passed to scandir(3) as a filter function.)
 
1209
 */
 
1210
int good_interface(const struct dirent *if_entry){
 
1211
  if(if_entry->d_name[0] == '.'){
 
1212
    return 0;
 
1213
  }
 
1214
  
 
1215
  struct ifreq ifr;
 
1216
  if(not get_flags(if_entry->d_name, &ifr)){
 
1217
    if(debug){
 
1218
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1219
              "Failed to get flags for interface \"%s\"\n",
 
1220
              if_entry->d_name);
 
1221
    }
 
1222
    return 0;
 
1223
  }
 
1224
  
 
1225
  if(not good_flags(if_entry->d_name, &ifr)){
 
1226
    return 0;
 
1227
  }
 
1228
  return 1;
 
1229
}
 
1230
 
 
1231
/* 
 
1232
 * This function determines if a directory entry in /sys/class/net
 
1233
 * corresponds to an acceptable network device which is up.
 
1234
 * (This function is passed to scandir(3) as a filter function.)
 
1235
 */
 
1236
int up_interface(const struct dirent *if_entry){
 
1237
  if(if_entry->d_name[0] == '.'){
 
1238
    return 0;
 
1239
  }
 
1240
  
 
1241
  struct ifreq ifr;
 
1242
  if(not get_flags(if_entry->d_name, &ifr)){
 
1243
    if(debug){
 
1244
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1245
              "Failed to get flags for interface \"%s\"\n",
 
1246
              if_entry->d_name);
 
1247
    }
 
1248
    return 0;
 
1249
  }
 
1250
  
 
1251
  /* Reject down interfaces */
 
1252
  if(not (ifr.ifr_flags & IFF_UP)){
 
1253
    if(debug){
 
1254
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1255
              "Rejecting down interface \"%s\"\n",
 
1256
              if_entry->d_name);
 
1257
    }
 
1258
    return 0;
 
1259
  }
 
1260
  
 
1261
  /* Reject non-running interfaces */
 
1262
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1263
    if(debug){
 
1264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1265
              "Rejecting non-running interface \"%s\"\n",
 
1266
              if_entry->d_name);
 
1267
    }
 
1268
    return 0;
 
1269
  }
 
1270
  
 
1271
  if(not good_flags(if_entry->d_name, &ifr)){
 
1272
    return 0;
 
1273
  }
 
1274
  return 1;
 
1275
}
 
1276
 
 
1277
int notdotentries(const struct dirent *direntry){
 
1278
  /* Skip "." and ".." */
 
1279
  if(direntry->d_name[0] == '.'
 
1280
     and (direntry->d_name[1] == '\0'
 
1281
          or (direntry->d_name[1] == '.'
 
1282
              and direntry->d_name[2] == '\0'))){
 
1283
    return 0;
 
1284
  }
 
1285
  return 1;
 
1286
}
 
1287
 
 
1288
/* Is this directory entry a runnable program? */
 
1289
int runnable_hook(const struct dirent *direntry){
 
1290
  int ret;
 
1291
  size_t sret;
 
1292
  struct stat st;
 
1293
  
 
1294
  if((direntry->d_name)[0] == '\0'){
 
1295
    /* Empty name? */
 
1296
    return 0;
 
1297
  }
 
1298
  
 
1299
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1300
                "abcdefghijklmnopqrstuvwxyz"
 
1301
                "0123456789"
 
1302
                "_-");
 
1303
  if((direntry->d_name)[sret] != '\0'){
 
1304
    /* Contains non-allowed characters */
 
1305
    if(debug){
 
1306
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1307
              "Ignoring hook \"%s\" with bad name\n",
 
1308
              direntry->d_name);
 
1309
    }
 
1310
    return 0;
 
1311
  }
 
1312
  
 
1313
  char *fullname = NULL;
 
1314
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1315
  if(ret < 0){
 
1316
    perror_plus("asprintf");
 
1317
    return 0;
 
1318
  }
 
1319
  
 
1320
  ret = stat(fullname, &st);
 
1321
  if(ret == -1){
 
1322
    if(debug){
 
1323
      perror_plus("Could not stat hook");
 
1324
    }
 
1325
    return 0;
 
1326
  }
 
1327
  if(not (S_ISREG(st.st_mode))){
 
1328
    /* Not a regular file */
 
1329
    if(debug){
 
1330
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1331
              "Ignoring hook \"%s\" - not a file\n",
 
1332
              direntry->d_name);
 
1333
    }
 
1334
    return 0;
 
1335
  }
 
1336
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1337
    /* Not executable */
 
1338
    if(debug){
 
1339
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1340
              "Ignoring hook \"%s\" - not executable\n",
 
1341
              direntry->d_name);
 
1342
    }
 
1343
    return 0;
 
1344
  }
 
1345
  return 1;
 
1346
}
 
1347
 
 
1348
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1349
  int ret;
 
1350
  struct timespec now;
 
1351
  struct timespec waited_time;
 
1352
  intmax_t block_time;
 
1353
  
 
1354
  while(true){
 
1355
    if(mc.current_server == NULL){
 
1356
      if (debug){
 
1357
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1358
                "Wait until first server is found. No timeout!\n");
 
1359
      }
 
1360
      ret = avahi_simple_poll_iterate(s, -1);
 
1361
    } else {
 
1362
      if (debug){
 
1363
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1364
                "Check current_server if we should run it,"
 
1365
                " or wait\n");
 
1366
      }
 
1367
      /* the current time */
 
1368
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
 
1369
      if(ret == -1){
 
1370
        perror_plus("clock_gettime");
 
1371
        return -1;
 
1372
      }
 
1373
      /* Calculating in ms how long time between now and server
 
1374
         who we visted longest time ago. Now - last seen.  */
 
1375
      waited_time.tv_sec = (now.tv_sec
 
1376
                            - mc.current_server->last_seen.tv_sec);
 
1377
      waited_time.tv_nsec = (now.tv_nsec
 
1378
                             - mc.current_server->last_seen.tv_nsec);
 
1379
      /* total time is 10s/10,000ms.
 
1380
         Converting to s from ms by dividing by 1,000,
 
1381
         and ns to ms by dividing by 1,000,000. */
 
1382
      block_time = ((retry_interval
 
1383
                     - ((intmax_t)waited_time.tv_sec * 1000))
 
1384
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
 
1385
      
 
1386
      if (debug){
 
1387
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1388
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1389
      }
 
1390
      
 
1391
      if(block_time <= 0){
 
1392
        ret = start_mandos_communication(mc.current_server->ip,
 
1393
                                         mc.current_server->port,
 
1394
                                         mc.current_server->if_index,
 
1395
                                         mc.current_server->af);
 
1396
        if(ret == 0){
 
1397
          avahi_simple_poll_quit(mc.simple_poll);
 
1398
          return 0;
 
1399
        }
 
1400
        ret = clock_gettime(CLOCK_MONOTONIC,
 
1401
                            &mc.current_server->last_seen);
 
1402
        if(ret == -1){
 
1403
          perror_plus("clock_gettime");
 
1404
          return -1;
 
1405
        }
 
1406
        mc.current_server = mc.current_server->next;
 
1407
        block_time = 0;         /* Call avahi to find new Mandos
 
1408
                                   servers, but don't block */
 
1409
      }
 
1410
      
 
1411
      ret = avahi_simple_poll_iterate(s, (int)block_time);
 
1412
    }
 
1413
    if(ret != 0){
 
1414
      if (ret > 0 or errno != EINTR){
 
1415
        return (ret != 1) ? ret : 0;
 
1416
      }
 
1417
    }
 
1418
  }
1120
1419
}
1121
1420
 
1122
1421
int main(int argc, char *argv[]){
1141
1440
  bool gnutls_initialized = false;
1142
1441
  bool gpgme_initialized = false;
1143
1442
  float delay = 2.5f;
 
1443
  double retry_interval = 10; /* 10s between trying a server and
 
1444
                                 retrying the same server again */
1144
1445
  
1145
1446
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
1447
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1152
1453
  errno = 0;
1153
1454
  ret = setgid(gid);
1154
1455
  if(ret == -1){
1155
 
    perror("setgid");
 
1456
    perror_plus("setgid");
1156
1457
  }
1157
1458
  
1158
1459
  /* Lower user privileges (temporarily) */
1159
1460
  errno = 0;
1160
1461
  ret = seteuid(uid);
1161
1462
  if(ret == -1){
1162
 
    perror("seteuid");
 
1463
    perror_plus("seteuid");
1163
1464
  }
1164
1465
  
1165
1466
  if(quit_now){
1200
1501
        .arg = "SECONDS",
1201
1502
        .doc = "Maximum delay to wait for interface startup",
1202
1503
        .group = 2 },
 
1504
      { .name = "retry", .key = 132,
 
1505
        .arg = "SECONDS",
 
1506
        .doc = "Retry interval used when denied by the mandos server",
 
1507
        .group = 2 },
 
1508
      { .name = "network-hook-dir", .key = 133,
 
1509
        .arg = "DIR",
 
1510
        .doc = "Directory where network hooks are located",
 
1511
        .group = 2 },
1203
1512
      /*
1204
1513
       * These reproduce what we would get without ARGP_NO_HELP
1205
1514
       */
1249
1558
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
1559
          argp_error(state, "Bad delay");
1251
1560
        }
 
1561
      case 132:                 /* --retry */
 
1562
        errno = 0;
 
1563
        retry_interval = strtod(arg, &tmp);
 
1564
        if(errno != 0 or tmp == arg or *tmp != '\0'
 
1565
           or (retry_interval * 1000) > INT_MAX
 
1566
           or retry_interval < 0){
 
1567
          argp_error(state, "Bad retry interval");
 
1568
        }
 
1569
        break;
 
1570
      case 133:                 /* --network-hook-dir */
 
1571
        hookdir = arg;
1252
1572
        break;
1253
1573
        /*
1254
1574
         * These reproduce what we would get without ARGP_NO_HELP
1261
1581
        argp_state_help(state, state->out_stream,
1262
1582
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1263
1583
      case 'V':                 /* --version */
 
1584
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1264
1585
        fprintf(state->out_stream, "%s\n", argp_program_version);
1265
1586
        exit(argp_err_exit_status);
1266
1587
        break;
1282
1603
    case ENOMEM:
1283
1604
    default:
1284
1605
      errno = ret;
1285
 
      perror("argp_parse");
 
1606
      perror_plus("argp_parse");
1286
1607
      exitcode = EX_OSERR;
1287
1608
      goto end;
1288
1609
    case EINVAL:
1290
1611
      goto end;
1291
1612
    }
1292
1613
  }
 
1614
    
 
1615
  {
 
1616
    /* Work around Debian bug #633582:
 
1617
       <http://bugs.debian.org/633582> */
 
1618
    struct stat st;
 
1619
    
 
1620
    /* Re-raise priviliges */
 
1621
    errno = 0;
 
1622
    ret = seteuid(0);
 
1623
    if(ret == -1){
 
1624
      perror_plus("seteuid");
 
1625
    }
 
1626
    
 
1627
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1628
      int seckey_fd = open(seckey, O_RDONLY);
 
1629
      if(seckey_fd == -1){
 
1630
        perror_plus("open");
 
1631
      } else {
 
1632
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1633
        if(ret == -1){
 
1634
          perror_plus("fstat");
 
1635
        } else {
 
1636
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1637
            ret = fchown(seckey_fd, uid, gid);
 
1638
            if(ret == -1){
 
1639
              perror_plus("fchown");
 
1640
            }
 
1641
          }
 
1642
        }
 
1643
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1644
      }
 
1645
    }
 
1646
    
 
1647
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1648
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1649
      if(pubkey_fd == -1){
 
1650
        perror_plus("open");
 
1651
      } else {
 
1652
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1653
        if(ret == -1){
 
1654
          perror_plus("fstat");
 
1655
        } else {
 
1656
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1657
            ret = fchown(pubkey_fd, uid, gid);
 
1658
            if(ret == -1){
 
1659
              perror_plus("fchown");
 
1660
            }
 
1661
          }
 
1662
        }
 
1663
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1664
      }
 
1665
    }
 
1666
    
 
1667
    /* Lower privileges */
 
1668
    errno = 0;
 
1669
    ret = seteuid(uid);
 
1670
    if(ret == -1){
 
1671
      perror_plus("seteuid");
 
1672
    }
 
1673
  }
 
1674
  
 
1675
  /* Find network hooks and run them */
 
1676
  {
 
1677
    struct dirent **direntries;
 
1678
    struct dirent *direntry;
 
1679
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1680
                           alphasort);
 
1681
    if(numhooks == -1){
 
1682
      perror_plus("scandir");
 
1683
    } else {
 
1684
      int devnull = open("/dev/null", O_RDONLY);
 
1685
      for(int i = 0; i < numhooks; i++){
 
1686
        direntry = direntries[0];
 
1687
        char *fullname = NULL;
 
1688
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1689
        if(ret < 0){
 
1690
          perror_plus("asprintf");
 
1691
          continue;
 
1692
        }
 
1693
        pid_t hook_pid = fork();
 
1694
        if(hook_pid == 0){
 
1695
          /* Child */
 
1696
          dup2(devnull, STDIN_FILENO);
 
1697
          close(devnull);
 
1698
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1699
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1700
          if(ret == -1){
 
1701
            perror_plus("setenv");
 
1702
            exit(1);
 
1703
          }
 
1704
          ret = setenv("DEVICE", interface, 1);
 
1705
          if(ret == -1){
 
1706
            perror_plus("setenv");
 
1707
            exit(1);
 
1708
          }
 
1709
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1710
          if(ret == -1){
 
1711
            perror_plus("setenv");
 
1712
            exit(1);
 
1713
          }
 
1714
          ret = setenv("MODE", "start", 1);
 
1715
          if(ret == -1){
 
1716
            perror_plus("setenv");
 
1717
            exit(1);
 
1718
          }
 
1719
          char *delaystring;
 
1720
          ret = asprintf(&delaystring, "%f", delay);
 
1721
          if(ret == -1){
 
1722
            perror_plus("asprintf");
 
1723
            exit(1);
 
1724
          }
 
1725
          ret = setenv("DELAY", delaystring, 1);
 
1726
          if(ret == -1){
 
1727
            free(delaystring);
 
1728
            perror_plus("setenv");
 
1729
            exit(1);
 
1730
          }
 
1731
          free(delaystring);
 
1732
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1733
          perror_plus("execl");
 
1734
        } else {
 
1735
          int status;
 
1736
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1737
            perror_plus("waitpid");
 
1738
            free(fullname);
 
1739
            continue;
 
1740
          }
 
1741
          if(WIFEXITED(status)){
 
1742
            if(WEXITSTATUS(status) != 0){
 
1743
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1744
                      "Warning: network hook \"%s\" exited"
 
1745
                      " with status %d\n", direntry->d_name,
 
1746
                      WEXITSTATUS(status));
 
1747
              free(fullname);
 
1748
              continue;
 
1749
            }
 
1750
          } else if(WIFSIGNALED(status)){
 
1751
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1752
                    "Warning: network hook \"%s\" died by"
 
1753
                    " signal %d\n", direntry->d_name,
 
1754
                    WTERMSIG(status));
 
1755
            free(fullname);
 
1756
            continue;
 
1757
          } else {
 
1758
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1759
                    "Warning: network hook \"%s\" crashed\n",
 
1760
                    direntry->d_name);
 
1761
            free(fullname);
 
1762
            continue;
 
1763
          }
 
1764
        }
 
1765
        free(fullname);
 
1766
        if(quit_now){
 
1767
          goto end;
 
1768
        }
 
1769
      }
 
1770
      close(devnull);
 
1771
    }
 
1772
  }
1293
1773
  
1294
1774
  if(not debug){
1295
1775
    avahi_set_log_function(empty_log);
1296
1776
  }
1297
 
 
 
1777
  
1298
1778
  if(interface[0] == '\0'){
1299
1779
    struct dirent **direntries;
1300
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1780
    /* First look for interfaces that are up */
 
1781
    ret = scandir(sys_class_net, &direntries, up_interface,
1301
1782
                  alphasort);
 
1783
    if(ret == 0){
 
1784
      /* No up interfaces, look for any good interfaces */
 
1785
      free(direntries);
 
1786
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1787
                    alphasort);
 
1788
    }
1302
1789
    if(ret >= 1){
1303
 
      /* Pick the first good interface */
 
1790
      /* Pick the first interface returned */
1304
1791
      interface = strdup(direntries[0]->d_name);
1305
1792
      if(debug){
1306
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1793
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1794
                "Using interface \"%s\"\n", interface);
1307
1795
      }
1308
1796
      if(interface == NULL){
1309
 
        perror("malloc");
 
1797
        perror_plus("malloc");
1310
1798
        free(direntries);
1311
1799
        exitcode = EXIT_FAILURE;
1312
1800
        goto end;
1314
1802
      free(direntries);
1315
1803
    } else {
1316
1804
      free(direntries);
1317
 
      fprintf(stderr, "Could not find a network interface\n");
 
1805
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1806
              "Could not find a network interface\n");
1318
1807
      exitcode = EXIT_FAILURE;
1319
1808
      goto end;
1320
1809
    }
1326
1815
  srand((unsigned int) time(NULL));
1327
1816
  mc.simple_poll = avahi_simple_poll_new();
1328
1817
  if(mc.simple_poll == NULL){
1329
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1818
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1819
            "Avahi: Failed to create simple poll object.\n");
1330
1820
    exitcode = EX_UNAVAILABLE;
1331
1821
    goto end;
1332
1822
  }
1334
1824
  sigemptyset(&sigterm_action.sa_mask);
1335
1825
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
1826
  if(ret == -1){
1337
 
    perror("sigaddset");
 
1827
    perror_plus("sigaddset");
1338
1828
    exitcode = EX_OSERR;
1339
1829
    goto end;
1340
1830
  }
1341
1831
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
1832
  if(ret == -1){
1343
 
    perror("sigaddset");
 
1833
    perror_plus("sigaddset");
1344
1834
    exitcode = EX_OSERR;
1345
1835
    goto end;
1346
1836
  }
1347
1837
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
1838
  if(ret == -1){
1349
 
    perror("sigaddset");
 
1839
    perror_plus("sigaddset");
1350
1840
    exitcode = EX_OSERR;
1351
1841
    goto end;
1352
1842
  }
1356
1846
  */
1357
1847
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
1848
  if(ret == -1){
1359
 
    perror("sigaction");
 
1849
    perror_plus("sigaction");
1360
1850
    return EX_OSERR;
1361
1851
  }
1362
1852
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
1853
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
1854
    if(ret == -1){
1365
 
      perror("sigaction");
 
1855
      perror_plus("sigaction");
1366
1856
      exitcode = EX_OSERR;
1367
1857
      goto end;
1368
1858
    }
1369
1859
  }
1370
1860
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
1861
  if(ret == -1){
1372
 
    perror("sigaction");
 
1862
    perror_plus("sigaction");
1373
1863
    return EX_OSERR;
1374
1864
  }
1375
1865
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
1866
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
1867
    if(ret == -1){
1378
 
      perror("sigaction");
 
1868
      perror_plus("sigaction");
1379
1869
      exitcode = EX_OSERR;
1380
1870
      goto end;
1381
1871
    }
1382
1872
  }
1383
1873
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
1874
  if(ret == -1){
1385
 
    perror("sigaction");
 
1875
    perror_plus("sigaction");
1386
1876
    return EX_OSERR;
1387
1877
  }
1388
1878
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
1879
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
1880
    if(ret == -1){
1391
 
      perror("sigaction");
 
1881
      perror_plus("sigaction");
1392
1882
      exitcode = EX_OSERR;
1393
1883
      goto end;
1394
1884
    }
1398
1888
  if(strcmp(interface, "none") != 0){
1399
1889
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1400
1890
    if(if_index == 0){
1401
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1891
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1892
              "No such interface: \"%s\"\n", interface);
1402
1893
      exitcode = EX_UNAVAILABLE;
1403
1894
      goto end;
1404
1895
    }
1411
1902
    errno = 0;
1412
1903
    ret = seteuid(0);
1413
1904
    if(ret == -1){
1414
 
      perror("seteuid");
 
1905
      perror_plus("seteuid");
1415
1906
    }
1416
1907
    
1417
1908
#ifdef __linux__
1421
1912
    bool restore_loglevel = true;
1422
1913
    if(ret == -1){
1423
1914
      restore_loglevel = false;
1424
 
      perror("klogctl");
 
1915
      perror_plus("klogctl");
1425
1916
    }
1426
1917
#endif  /* __linux__ */
1427
1918
    
1428
1919
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
1920
    if(sd < 0){
1430
 
      perror("socket");
 
1921
      perror_plus("socket");
1431
1922
      exitcode = EX_OSERR;
1432
1923
#ifdef __linux__
1433
1924
      if(restore_loglevel){
1434
1925
        ret = klogctl(7, NULL, 0);
1435
1926
        if(ret == -1){
1436
 
          perror("klogctl");
 
1927
          perror_plus("klogctl");
1437
1928
        }
1438
1929
      }
1439
1930
#endif  /* __linux__ */
1441
1932
      errno = 0;
1442
1933
      ret = seteuid(uid);
1443
1934
      if(ret == -1){
1444
 
        perror("seteuid");
 
1935
        perror_plus("seteuid");
1445
1936
      }
1446
1937
      goto end;
1447
1938
    }
1448
1939
    strcpy(network.ifr_name, interface);
1449
1940
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
1941
    if(ret == -1){
1451
 
      perror("ioctl SIOCGIFFLAGS");
 
1942
      perror_plus("ioctl SIOCGIFFLAGS");
1452
1943
#ifdef __linux__
1453
1944
      if(restore_loglevel){
1454
1945
        ret = klogctl(7, NULL, 0);
1455
1946
        if(ret == -1){
1456
 
          perror("klogctl");
 
1947
          perror_plus("klogctl");
1457
1948
        }
1458
1949
      }
1459
1950
#endif  /* __linux__ */
1462
1953
      errno = 0;
1463
1954
      ret = seteuid(uid);
1464
1955
      if(ret == -1){
1465
 
        perror("seteuid");
 
1956
        perror_plus("seteuid");
1466
1957
      }
1467
1958
      goto end;
1468
1959
    }
1472
1963
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
1964
      if(ret == -1){
1474
1965
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1966
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1476
1967
        exitcode = EX_OSERR;
1477
1968
#ifdef __linux__
1478
1969
        if(restore_loglevel){
1479
1970
          ret = klogctl(7, NULL, 0);
1480
1971
          if(ret == -1){
1481
 
            perror("klogctl");
 
1972
            perror_plus("klogctl");
1482
1973
          }
1483
1974
        }
1484
1975
#endif  /* __linux__ */
1486
1977
        errno = 0;
1487
1978
        ret = seteuid(uid);
1488
1979
        if(ret == -1){
1489
 
          perror("seteuid");
 
1980
          perror_plus("seteuid");
1490
1981
        }
1491
1982
        goto end;
1492
1983
      }
1493
1984
    }
1494
 
    /* sleep checking until interface is running */
 
1985
    /* Sleep checking until interface is running.
 
1986
       Check every 0.25s, up to total time of delay */
1495
1987
    for(int i=0; i < delay * 4; i++){
1496
1988
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
1989
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
 
1990
        perror_plus("ioctl SIOCGIFFLAGS");
1499
1991
      } else if(network.ifr_flags & IFF_RUNNING){
1500
1992
        break;
1501
1993
      }
1502
1994
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
1995
      ret = nanosleep(&sleeptime, NULL);
1504
1996
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
 
1997
        perror_plus("nanosleep");
1506
1998
      }
1507
1999
    }
1508
2000
    if(not take_down_interface){
1509
2001
      /* We won't need the socket anymore */
1510
2002
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
2003
      if(ret == -1){
1512
 
        perror("close");
 
2004
        perror_plus("close");
1513
2005
      }
1514
2006
    }
1515
2007
#ifdef __linux__
1517
2009
      /* Restores kernel loglevel to default */
1518
2010
      ret = klogctl(7, NULL, 0);
1519
2011
      if(ret == -1){
1520
 
        perror("klogctl");
 
2012
        perror_plus("klogctl");
1521
2013
      }
1522
2014
    }
1523
2015
#endif  /* __linux__ */
1527
2019
      /* Lower privileges */
1528
2020
      ret = seteuid(uid);
1529
2021
      if(ret == -1){
1530
 
        perror("seteuid");
 
2022
        perror_plus("seteuid");
1531
2023
      }
1532
2024
    } else {
1533
2025
      /* Lower privileges permanently */
1534
2026
      ret = setuid(uid);
1535
2027
      if(ret == -1){
1536
 
        perror("setuid");
 
2028
        perror_plus("setuid");
1537
2029
      }
1538
2030
    }
1539
2031
  }
1544
2036
  
1545
2037
  ret = init_gnutls_global(pubkey, seckey);
1546
2038
  if(ret == -1){
1547
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2039
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2040
            "init_gnutls_global failed\n");
1548
2041
    exitcode = EX_UNAVAILABLE;
1549
2042
    goto end;
1550
2043
  } else {
1555
2048
    goto end;
1556
2049
  }
1557
2050
  
 
2051
  if(mkdtemp(tempdir) == NULL){
 
2052
    perror_plus("mkdtemp");
 
2053
    goto end;
 
2054
  }
1558
2055
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
2056
  
1565
2057
  if(quit_now){
1566
2058
    goto end;
1567
2059
  }
1568
2060
  
1569
2061
  if(not init_gpgme(pubkey, seckey, tempdir)){
1570
 
    fprintf(stderr, "init_gpgme failed\n");
 
2062
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2063
            "init_gpgme failed\n");
1571
2064
    exitcode = EX_UNAVAILABLE;
1572
2065
    goto end;
1573
2066
  } else {
1583
2076
    /* (Mainly meant for debugging) */
1584
2077
    char *address = strrchr(connect_to, ':');
1585
2078
    if(address == NULL){
1586
 
      fprintf(stderr, "No colon in address\n");
 
2079
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2080
              "No colon in address\n");
1587
2081
      exitcode = EX_USAGE;
1588
2082
      goto end;
1589
2083
    }
1597
2091
    tmpmax = strtoimax(address+1, &tmp, 10);
1598
2092
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1599
2093
       or tmpmax != (uint16_t)tmpmax){
1600
 
      fprintf(stderr, "Bad port number\n");
 
2094
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2095
              "Bad port number\n");
1601
2096
      exitcode = EX_USAGE;
1602
2097
      goto end;
1603
2098
    }
1608
2103
    
1609
2104
    port = (uint16_t)tmpmax;
1610
2105
    *address = '\0';
1611
 
    address = connect_to;
1612
2106
    /* Colon in address indicates IPv6 */
1613
2107
    int af;
1614
 
    if(strchr(address, ':') != NULL){
 
2108
    if(strchr(connect_to, ':') != NULL){
1615
2109
      af = AF_INET6;
 
2110
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2111
      if(connect_to[0] == '[' and address[-1] == ']')
 
2112
        {
 
2113
          connect_to++;
 
2114
          address[-1] = '\0';
 
2115
        }
1616
2116
    } else {
1617
2117
      af = AF_INET;
1618
2118
    }
 
2119
    address = connect_to;
1619
2120
    
1620
2121
    if(quit_now){
1621
2122
      goto end;
1622
2123
    }
1623
 
 
 
2124
    
1624
2125
    while(not quit_now){
1625
2126
      ret = start_mandos_communication(address, port, if_index, af);
1626
2127
      if(quit_now or ret == 0){
1627
2128
        break;
1628
2129
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
 
2130
      if(debug){
 
2131
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2132
                "Retrying in %d seconds\n", (int)retry_interval);
 
2133
      }
 
2134
      sleep((int)retry_interval);
 
2135
    }
 
2136
    
1632
2137
    if (not quit_now){
1633
2138
      exitcode = EXIT_SUCCESS;
1634
2139
    }
1635
 
 
 
2140
    
1636
2141
    goto end;
1637
2142
  }
1638
2143
  
1660
2165
  
1661
2166
  /* Check if creating the Avahi server object succeeded */
1662
2167
  if(mc.server == NULL){
1663
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2168
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2169
            "Failed to create Avahi server: %s\n",
1664
2170
            avahi_strerror(error));
1665
2171
    exitcode = EX_UNAVAILABLE;
1666
2172
    goto end;
1675
2181
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1676
2182
                                   NULL, 0, browse_callback, NULL);
1677
2183
  if(sb == NULL){
1678
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2184
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2185
            "Failed to create service browser: %s\n",
1679
2186
            avahi_strerror(avahi_server_errno(mc.server)));
1680
2187
    exitcode = EX_UNAVAILABLE;
1681
2188
    goto end;
1688
2195
  /* Run the main loop */
1689
2196
  
1690
2197
  if(debug){
1691
 
    fprintf(stderr, "Starting Avahi loop search\n");
1692
 
  }
1693
 
  
1694
 
  avahi_simple_poll_loop(mc.simple_poll);
 
2198
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2199
            "Starting Avahi loop search\n");
 
2200
  }
 
2201
 
 
2202
  ret = avahi_loop_with_timeout(mc.simple_poll,
 
2203
                                (int)(retry_interval * 1000));
 
2204
  if(debug){
 
2205
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2206
            "avahi_loop_with_timeout exited %s\n",
 
2207
            (ret == 0) ? "successfully" : "with error");
 
2208
  }
1695
2209
  
1696
2210
 end:
1697
2211
  
1698
2212
  if(debug){
1699
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2213
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2214
            "%s exiting\n", argv[0]);
1700
2215
  }
1701
2216
  
1702
2217
  /* Cleanup things */
1718
2233
  if(gpgme_initialized){
1719
2234
    gpgme_release(mc.ctx);
1720
2235
  }
 
2236
 
 
2237
  /* Cleans up the circular linked list of Mandos servers the client
 
2238
     has seen */
 
2239
  if(mc.current_server != NULL){
 
2240
    mc.current_server->prev->next = NULL;
 
2241
    while(mc.current_server != NULL){
 
2242
      server *next = mc.current_server->next;
 
2243
      free(mc.current_server);
 
2244
      mc.current_server = next;
 
2245
    }
 
2246
  }
 
2247
  
 
2248
  /* XXX run network hooks "stop" here  */
1721
2249
  
1722
2250
  /* Take down the network interface */
1723
2251
  if(take_down_interface){
1725
2253
    errno = 0;
1726
2254
    ret = seteuid(0);
1727
2255
    if(ret == -1){
1728
 
      perror("seteuid");
 
2256
      perror_plus("seteuid");
1729
2257
    }
1730
2258
    if(geteuid() == 0){
1731
2259
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
2260
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
1734
 
      } else if(network.ifr_flags & IFF_UP) {
 
2261
        perror_plus("ioctl SIOCGIFFLAGS");
 
2262
      } else if(network.ifr_flags & IFF_UP){
1735
2263
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
2264
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
2265
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
2266
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1739
2267
        }
1740
2268
      }
1741
2269
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
2270
      if(ret == -1){
1743
 
        perror("close");
 
2271
        perror_plus("close");
1744
2272
      }
1745
2273
      /* Lower privileges permanently */
1746
2274
      errno = 0;
1747
2275
      ret = setuid(uid);
1748
2276
      if(ret == -1){
1749
 
        perror("setuid");
 
2277
        perror_plus("setuid");
1750
2278
      }
1751
2279
    }
1752
2280
  }
1753
2281
  
1754
 
  /* Removes the temp directory used by GPGME */
 
2282
  /* Removes the GPGME temp directory and all files inside */
1755
2283
  if(tempdir_created){
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
 
        }
 
2284
    struct dirent **direntries = NULL;
 
2285
    struct dirent *direntry = NULL;
 
2286
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2287
                             alphasort);
 
2288
    if (numentries > 0){
 
2289
      for(int i = 0; i < numentries; i++){
 
2290
        direntry = direntries[i];
1776
2291
        char *fullname = NULL;
1777
2292
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
2293
                       direntry->d_name);
1779
2294
        if(ret < 0){
1780
 
          perror("asprintf");
 
2295
          perror_plus("asprintf");
1781
2296
          continue;
1782
2297
        }
1783
2298
        ret = remove(fullname);
1784
2299
        if(ret == -1){
1785
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1786
 
                  strerror(errno));
 
2300
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2301
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
1787
2302
        }
1788
2303
        free(fullname);
1789
2304
      }
1790
 
      closedir(d);
 
2305
    }
 
2306
 
 
2307
    /* need to clean even if 0 because man page doesn't specify */
 
2308
    free(direntries);
 
2309
    if (numentries == -1){
 
2310
      perror_plus("scandir");
1791
2311
    }
1792
2312
    ret = rmdir(tempdir);
1793
2313
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
 
2314
      perror_plus("rmdir");
1795
2315
    }
1796
2316
  }
1797
2317
  
1802
2322
                                            &old_sigterm_action,
1803
2323
                                            NULL));
1804
2324
    if(ret == -1){
1805
 
      perror("sigaction");
 
2325
      perror_plus("sigaction");
1806
2326
    }
1807
2327
    do {
1808
2328
      ret = raise(signal_received);
1809
2329
    } while(ret != 0 and errno == EINTR);
1810
2330
    if(ret != 0){
1811
 
      perror("raise");
 
2331
      perror_plus("raise");
1812
2332
      abort();
1813
2333
    }
1814
2334
    TEMP_FAILURE_RETRY(pause());