/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

* plugins.d/mandos-client.c (run_network_hooks): New.
  (main): Run run_network_hooks() with "stop" and "start" at
          appropriate places.  Don't lower privileges permanently
          prematurely.

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