/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2009-09-17 04:16:32 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090917041632-7m1rm83pxguw5zw7
* plugins.d/usplash.c (main): Bug fix: only close FIFO if opened.

Show diffs side-by-side

added added

removed removed

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