/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 (SYNOPSIS, OPTIONS): Document
                                                 "--network-hook-dir"
                                                 option.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008,2009 Teddy Hogeborn
13
 
 * Copyright © 2008,2009 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
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, EXIT_FAILURE,
47
 
                                   srand(), strtof() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
 
47
                                   strtof(), abort() */
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() */
 
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 */
66
 
#include <time.h>               /* nanosleep(), time() */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
 
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
69
70
                                   if_nametoindex(), IF_NAMESIZE */
71
72
                                   INET_ADDRSTRLEN, INET6_ADDRSTRLEN
72
73
                                */
73
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
 
                                   getuid(), getgid(), setuid(),
75
 
                                   setgid() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons */
 
75
                                   getuid(), getgid(), seteuid(),
 
76
                                   setgid(), pause() */
 
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,
82
83
#include <signal.h>             /* sigemptyset(), sigaddset(),
83
84
                                   sigaction(), SIGTERM, sig_atomic_t,
84
85
                                   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() */
85
90
 
86
91
#ifdef __linux__
87
92
#include <sys/klog.h>           /* klogctl() */
120
125
#define PATHDIR "/conf/conf.d/mandos"
121
126
#define SECKEY "seckey.txt"
122
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
123
129
 
124
130
bool debug = false;
125
131
static const char mandos_protocol_version[] = "1";
126
132
const char *argp_program_version = "mandos-client " VERSION;
127
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
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;
128
148
 
129
149
/* Used for passing in values through the Avahi callback functions */
130
150
typedef struct {
135
155
  gnutls_dh_params_t dh_params;
136
156
  const char *priority;
137
157
  gpgme_ctx_t ctx;
 
158
  server *current_server;
138
159
} mandos_context;
139
160
 
140
161
/* global context so signal handler can reach it*/
141
162
mandos_context mc = { .simple_poll = NULL, .server = NULL,
142
163
                      .dh_bits = 1024, .priority = "SECURE256"
143
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
164
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
165
                      .current_server = NULL };
 
166
 
 
167
sig_atomic_t quit_now = 0;
 
168
int signal_received = 0;
 
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
}
144
176
 
145
177
/*
146
178
 * Make additional room in "buffer" for at least BUFFER_SIZE more
159
191
  return buffer_capacity;
160
192
}
161
193
 
 
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
 
162
232
/* 
163
233
 * Initialize GPGME.
164
234
 */
178
248
    
179
249
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
180
250
    if(fd == -1){
181
 
      perror("open");
 
251
      perror_plus("open");
182
252
      return false;
183
253
    }
184
254
    
185
255
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
186
256
    if(rc != GPG_ERR_NO_ERROR){
187
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
257
      fprintf(stderr, "Mandos plugin mandos-client: "
 
258
              "bad gpgme_data_new_from_fd: %s: %s\n",
188
259
              gpgme_strsource(rc), gpgme_strerror(rc));
189
260
      return false;
190
261
    }
191
262
    
192
263
    rc = gpgme_op_import(mc.ctx, pgp_data);
193
264
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
265
      fprintf(stderr, "Mandos plugin mandos-client: "
 
266
              "bad gpgme_op_import: %s: %s\n",
195
267
              gpgme_strsource(rc), gpgme_strerror(rc));
196
268
      return false;
197
269
    }
198
270
    
199
271
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
200
272
    if(ret == -1){
201
 
      perror("close");
 
273
      perror_plus("close");
202
274
    }
203
275
    gpgme_data_release(pgp_data);
204
276
    return true;
205
277
  }
206
278
  
207
279
  if(debug){
208
 
    fprintf(stderr, "Initializing GPGME\n");
 
280
    fprintf(stderr, "Mandos plugin mandos-client: "
 
281
            "Initializing GPGME\n");
209
282
  }
210
283
  
211
284
  /* Init GPGME */
212
285
  gpgme_check_version(NULL);
213
286
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
214
287
  if(rc != GPG_ERR_NO_ERROR){
215
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
288
    fprintf(stderr, "Mandos plugin mandos-client: "
 
289
            "bad gpgme_engine_check_version: %s: %s\n",
216
290
            gpgme_strsource(rc), gpgme_strerror(rc));
217
291
    return false;
218
292
  }
219
293
  
220
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
294
  /* Set GPGME home directory for the OpenPGP engine only */
221
295
  rc = gpgme_get_engine_info(&engine_info);
222
296
  if(rc != GPG_ERR_NO_ERROR){
223
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
297
    fprintf(stderr, "Mandos plugin mandos-client: "
 
298
            "bad gpgme_get_engine_info: %s: %s\n",
224
299
            gpgme_strsource(rc), gpgme_strerror(rc));
225
300
    return false;
226
301
  }
233
308
    engine_info = engine_info->next;
234
309
  }
235
310
  if(engine_info == NULL){
236
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
311
    fprintf(stderr, "Mandos plugin mandos-client: "
 
312
            "Could not set GPGME home dir to %s\n", tempdir);
237
313
    return false;
238
314
  }
239
315
  
240
316
  /* Create new GPGME "context" */
241
317
  rc = gpgme_new(&(mc.ctx));
242
318
  if(rc != GPG_ERR_NO_ERROR){
243
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
244
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
319
    fprintf(stderr, "Mandos plugin mandos-client: "
 
320
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
321
            gpgme_strerror(rc));
245
322
    return false;
246
323
  }
247
324
  
266
343
  ssize_t plaintext_length = 0;
267
344
  
268
345
  if(debug){
269
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
346
    fprintf(stderr, "Mandos plugin mandos-client: "
 
347
            "Trying to decrypt OpenPGP data\n");
270
348
  }
271
349
  
272
350
  /* Create new GPGME data buffer from memory cryptotext */
273
351
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
274
352
                               0);
275
353
  if(rc != GPG_ERR_NO_ERROR){
276
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
354
    fprintf(stderr, "Mandos plugin mandos-client: "
 
355
            "bad gpgme_data_new_from_mem: %s: %s\n",
277
356
            gpgme_strsource(rc), gpgme_strerror(rc));
278
357
    return -1;
279
358
  }
281
360
  /* Create new empty GPGME data buffer for the plaintext */
282
361
  rc = gpgme_data_new(&dh_plain);
283
362
  if(rc != GPG_ERR_NO_ERROR){
284
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
363
    fprintf(stderr, "Mandos plugin mandos-client: "
 
364
            "bad gpgme_data_new: %s: %s\n",
285
365
            gpgme_strsource(rc), gpgme_strerror(rc));
286
366
    gpgme_data_release(dh_crypto);
287
367
    return -1;
291
371
     data buffer */
292
372
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
293
373
  if(rc != GPG_ERR_NO_ERROR){
294
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
374
    fprintf(stderr, "Mandos plugin mandos-client: "
 
375
            "bad gpgme_op_decrypt: %s: %s\n",
295
376
            gpgme_strsource(rc), gpgme_strerror(rc));
296
377
    plaintext_length = -1;
297
378
    if(debug){
298
379
      gpgme_decrypt_result_t result;
299
380
      result = gpgme_op_decrypt_result(mc.ctx);
300
381
      if(result == NULL){
301
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
382
        fprintf(stderr, "Mandos plugin mandos-client: "
 
383
                "gpgme_op_decrypt_result failed\n");
302
384
      } else {
303
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
385
        fprintf(stderr, "Mandos plugin mandos-client: "
 
386
                "Unsupported algorithm: %s\n",
304
387
                result->unsupported_algorithm);
305
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
388
        fprintf(stderr, "Mandos plugin mandos-client: "
 
389
                "Wrong key usage: %u\n",
306
390
                result->wrong_key_usage);
307
391
        if(result->file_name != NULL){
308
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
392
          fprintf(stderr, "Mandos plugin mandos-client: "
 
393
                  "File name: %s\n", result->file_name);
309
394
        }
310
395
        gpgme_recipient_t recipient;
311
396
        recipient = result->recipients;
312
397
        while(recipient != NULL){
313
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
398
          fprintf(stderr, "Mandos plugin mandos-client: "
 
399
                  "Public key algorithm: %s\n",
314
400
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
315
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
316
 
          fprintf(stderr, "Secret key available: %s\n",
 
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",
317
405
                  recipient->status == GPG_ERR_NO_SECKEY
318
406
                  ? "No" : "Yes");
319
407
          recipient = recipient->next;
324
412
  }
325
413
  
326
414
  if(debug){
327
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
415
    fprintf(stderr, "Mandos plugin mandos-client: "
 
416
            "Decryption of OpenPGP data succeeded\n");
328
417
  }
329
418
  
330
419
  /* Seek back to the beginning of the GPGME plaintext data buffer */
331
420
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
332
 
    perror("gpgme_data_seek");
 
421
    perror_plus("gpgme_data_seek");
333
422
    plaintext_length = -1;
334
423
    goto decrypt_end;
335
424
  }
340
429
                                      (size_t)plaintext_length,
341
430
                                      plaintext_capacity);
342
431
    if(plaintext_capacity == 0){
343
 
        perror("incbuffer");
 
432
        perror_plus("incbuffer");
344
433
        plaintext_length = -1;
345
434
        goto decrypt_end;
346
435
    }
353
442
      break;
354
443
    }
355
444
    if(ret < 0){
356
 
      perror("gpgme_data_read");
 
445
      perror_plus("gpgme_data_read");
357
446
      plaintext_length = -1;
358
447
      goto decrypt_end;
359
448
    }
361
450
  }
362
451
  
363
452
  if(debug){
364
 
    fprintf(stderr, "Decrypted password is: ");
 
453
    fprintf(stderr, "Mandos plugin mandos-client: "
 
454
            "Decrypted password is: ");
365
455
    for(ssize_t i = 0; i < plaintext_length; i++){
366
456
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
367
457
    }
389
479
/* GnuTLS log function callback */
390
480
static void debuggnutls(__attribute__((unused)) int level,
391
481
                        const char* string){
392
 
  fprintf(stderr, "GnuTLS: %s", string);
 
482
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
393
483
}
394
484
 
395
485
static int init_gnutls_global(const char *pubkeyfilename,
397
487
  int ret;
398
488
  
399
489
  if(debug){
400
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
490
    fprintf(stderr, "Mandos plugin mandos-client: "
 
491
            "Initializing GnuTLS\n");
401
492
  }
402
493
  
403
494
  ret = gnutls_global_init();
404
495
  if(ret != GNUTLS_E_SUCCESS){
405
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
406
 
            safer_gnutls_strerror(ret));
 
496
    fprintf(stderr, "Mandos plugin mandos-client: "
 
497
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
407
498
    return -1;
408
499
  }
409
500
  
416
507
  }
417
508
  
418
509
  /* OpenPGP credentials */
419
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
510
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
420
511
  if(ret != GNUTLS_E_SUCCESS){
421
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
422
 
                                                    from
423
 
                                                    -Wunreachable-code
424
 
                                                 */
425
 
            safer_gnutls_strerror(ret));
 
512
    fprintf(stderr, "Mandos plugin mandos-client: "
 
513
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
426
514
    gnutls_global_deinit();
427
515
    return -1;
428
516
  }
429
517
  
430
518
  if(debug){
431
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
519
    fprintf(stderr, "Mandos plugin mandos-client: "
 
520
            "Attempting to use OpenPGP public key %s and"
432
521
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
433
522
            seckeyfilename);
434
523
  }
438
527
     GNUTLS_OPENPGP_FMT_BASE64);
439
528
  if(ret != GNUTLS_E_SUCCESS){
440
529
    fprintf(stderr,
 
530
            "Mandos plugin mandos-client: "
441
531
            "Error[%d] while reading the OpenPGP key pair ('%s',"
442
532
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
443
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
444
 
            safer_gnutls_strerror(ret));
 
533
    fprintf(stderr, "Mandos plugin mandos-client: "
 
534
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
445
535
    goto globalfail;
446
536
  }
447
537
  
448
538
  /* GnuTLS server initialization */
449
539
  ret = gnutls_dh_params_init(&mc.dh_params);
450
540
  if(ret != GNUTLS_E_SUCCESS){
451
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
541
    fprintf(stderr, "Mandos plugin mandos-client: "
 
542
            "Error in GnuTLS DH parameter initialization:"
452
543
            " %s\n", safer_gnutls_strerror(ret));
453
544
    goto globalfail;
454
545
  }
455
546
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
456
547
  if(ret != GNUTLS_E_SUCCESS){
457
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
548
    fprintf(stderr, "Mandos plugin mandos-client: "
 
549
            "Error in GnuTLS prime generation: %s\n",
458
550
            safer_gnutls_strerror(ret));
459
551
    goto globalfail;
460
552
  }
474
566
static int init_gnutls_session(gnutls_session_t *session){
475
567
  int ret;
476
568
  /* GnuTLS session creation */
477
 
  ret = gnutls_init(session, GNUTLS_SERVER);
 
569
  do {
 
570
    ret = gnutls_init(session, GNUTLS_SERVER);
 
571
    if(quit_now){
 
572
      return -1;
 
573
    }
 
574
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
478
575
  if(ret != GNUTLS_E_SUCCESS){
479
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
576
    fprintf(stderr, "Mandos plugin mandos-client: "
 
577
            "Error in GnuTLS session initialization: %s\n",
480
578
            safer_gnutls_strerror(ret));
481
579
  }
482
580
  
483
581
  {
484
582
    const char *err;
485
 
    ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
583
    do {
 
584
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
585
      if(quit_now){
 
586
        gnutls_deinit(*session);
 
587
        return -1;
 
588
      }
 
589
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
486
590
    if(ret != GNUTLS_E_SUCCESS){
487
 
      fprintf(stderr, "Syntax error at: %s\n", err);
488
 
      fprintf(stderr, "GnuTLS error: %s\n",
489
 
              safer_gnutls_strerror(ret));
 
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));
490
595
      gnutls_deinit(*session);
491
596
      return -1;
492
597
    }
493
598
  }
494
599
  
495
 
  ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
496
 
                               mc.cred);
 
600
  do {
 
601
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
 
602
                                 mc.cred);
 
603
    if(quit_now){
 
604
      gnutls_deinit(*session);
 
605
      return -1;
 
606
    }
 
607
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
497
608
  if(ret != GNUTLS_E_SUCCESS){
498
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
609
    fprintf(stderr, "Mandos plugin mandos-client: "
 
610
            "Error setting GnuTLS credentials: %s\n",
499
611
            safer_gnutls_strerror(ret));
500
612
    gnutls_deinit(*session);
501
613
    return -1;
502
614
  }
503
615
  
504
616
  /* ignore client certificate if any. */
505
 
  gnutls_certificate_server_set_request(*session,
506
 
                                        GNUTLS_CERT_IGNORE);
 
617
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
507
618
  
508
619
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
509
620
  
514
625
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
515
626
                      __attribute__((unused)) const char *txt){}
516
627
 
517
 
sig_atomic_t quit_now = 0;
518
 
int signal_received = 0;
519
 
 
520
628
/* Called when a Mandos server is found */
521
629
static int start_mandos_communication(const char *ip, uint16_t port,
522
630
                                      AvahiIfIndex if_index,
528
636
    struct sockaddr_in6 in6;
529
637
  } to;
530
638
  char *buffer = NULL;
531
 
  char *decrypted_buffer;
 
639
  char *decrypted_buffer = NULL;
532
640
  size_t buffer_length = 0;
533
641
  size_t buffer_capacity = 0;
534
642
  size_t written;
535
 
  int retval = 0;
 
643
  int retval = -1;
536
644
  gnutls_session_t session;
537
645
  int pf;                       /* Protocol family */
538
646
  
 
647
  errno = 0;
 
648
  
539
649
  if(quit_now){
 
650
    errno = EINTR;
540
651
    return -1;
541
652
  }
542
653
  
548
659
    pf = PF_INET;
549
660
    break;
550
661
  default:
551
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
662
    fprintf(stderr, "Mandos plugin mandos-client: "
 
663
            "Bad address family: %d\n", af);
 
664
    errno = EINVAL;
552
665
    return -1;
553
666
  }
554
667
  
558
671
  }
559
672
  
560
673
  if(debug){
561
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
674
    fprintf(stderr, "Mandos plugin mandos-client: "
 
675
            "Setting up a TCP connection to %s, port %" PRIu16
562
676
            "\n", ip, port);
563
677
  }
564
678
  
565
679
  tcp_sd = socket(pf, SOCK_STREAM, 0);
566
680
  if(tcp_sd < 0){
567
 
    perror("socket");
568
 
    retval = -1;
 
681
    int e = errno;
 
682
    perror_plus("socket");
 
683
    errno = e;
569
684
    goto mandos_end;
570
685
  }
571
686
  
572
687
  if(quit_now){
 
688
    errno = EINTR;
573
689
    goto mandos_end;
574
690
  }
575
691
  
582
698
    ret = inet_pton(af, ip, &to.in.sin_addr);
583
699
  }
584
700
  if(ret < 0 ){
585
 
    perror("inet_pton");
586
 
    retval = -1;
 
701
    int e = errno;
 
702
    perror_plus("inet_pton");
 
703
    errno = e;
587
704
    goto mandos_end;
588
705
  }
589
706
  if(ret == 0){
590
 
    fprintf(stderr, "Bad address: %s\n", ip);
591
 
    retval = -1;
 
707
    int e = errno;
 
708
    fprintf(stderr, "Mandos plugin mandos-client: "
 
709
            "Bad address: %s\n", ip);
 
710
    errno = e;
592
711
    goto mandos_end;
593
712
  }
594
713
  if(af == AF_INET6){
600
719
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
601
720
                              -Wunreachable-code*/
602
721
      if(if_index == AVAHI_IF_UNSPEC){
603
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
722
        fprintf(stderr, "Mandos plugin mandos-client: "
 
723
                "An IPv6 link-local address is incomplete"
604
724
                " without a network interface\n");
605
 
        retval = -1;
 
725
        errno = EINVAL;
606
726
        goto mandos_end;
607
727
      }
608
728
      /* Set the network interface number as scope */
615
735
  }
616
736
  
617
737
  if(quit_now){
 
738
    errno = EINTR;
618
739
    goto mandos_end;
619
740
  }
620
741
  
622
743
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
623
744
      char interface[IF_NAMESIZE];
624
745
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
625
 
        perror("if_indextoname");
 
746
        perror_plus("if_indextoname");
626
747
      } else {
627
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
748
        fprintf(stderr, "Mandos plugin mandos-client: "
 
749
                "Connection to: %s%%%s, port %" PRIu16 "\n",
628
750
                ip, interface, port);
629
751
      }
630
752
    } else {
631
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
632
 
              port);
 
753
      fprintf(stderr, "Mandos plugin mandos-client: "
 
754
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
633
755
    }
634
756
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
635
757
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
642
764
                        sizeof(addrstr));
643
765
    }
644
766
    if(pcret == NULL){
645
 
      perror("inet_ntop");
 
767
      perror_plus("inet_ntop");
646
768
    } else {
647
769
      if(strcmp(addrstr, ip) != 0){
648
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
770
        fprintf(stderr, "Mandos plugin mandos-client: "
 
771
                "Canonical address form: %s\n", addrstr);
649
772
      }
650
773
    }
651
774
  }
652
775
  
653
776
  if(quit_now){
 
777
    errno = EINTR;
654
778
    goto mandos_end;
655
779
  }
656
780
  
660
784
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
661
785
  }
662
786
  if(ret < 0){
663
 
    perror("connect");
664
 
    retval = -1;
 
787
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
788
      int e = errno;
 
789
      perror_plus("connect");
 
790
      errno = e;
 
791
    }
665
792
    goto mandos_end;
666
793
  }
667
794
  
668
795
  if(quit_now){
 
796
    errno = EINTR;
669
797
    goto mandos_end;
670
798
  }
671
799
  
676
804
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
677
805
                                   out_size - written));
678
806
    if(ret == -1){
679
 
      perror("write");
680
 
      retval = -1;
 
807
      int e = errno;
 
808
      perror_plus("write");
 
809
      errno = e;
681
810
      goto mandos_end;
682
811
    }
683
812
    written += (size_t)ret;
693
822
    }
694
823
  
695
824
    if(quit_now){
 
825
      errno = EINTR;
696
826
      goto mandos_end;
697
827
    }
698
828
  }
699
829
  
700
830
  if(debug){
701
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
831
    fprintf(stderr, "Mandos plugin mandos-client: "
 
832
            "Establishing TLS session with %s\n", ip);
702
833
  }
703
834
  
704
835
  if(quit_now){
 
836
    errno = EINTR;
705
837
    goto mandos_end;
706
838
  }
707
839
  
 
840
  /* Spurious warning from -Wint-to-pointer-cast */
708
841
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
709
842
  
710
843
  if(quit_now){
 
844
    errno = EINTR;
711
845
    goto mandos_end;
712
846
  }
713
847
  
714
848
  do {
715
849
    ret = gnutls_handshake(session);
716
850
    if(quit_now){
 
851
      errno = EINTR;
717
852
      goto mandos_end;
718
853
    }
719
854
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
720
855
  
721
856
  if(ret != GNUTLS_E_SUCCESS){
722
857
    if(debug){
723
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
858
      fprintf(stderr, "Mandos plugin mandos-client: "
 
859
              "*** GnuTLS Handshake failed ***\n");
724
860
      gnutls_perror(ret);
725
861
    }
726
 
    retval = -1;
 
862
    errno = EPROTO;
727
863
    goto mandos_end;
728
864
  }
729
865
  
730
866
  /* Read OpenPGP packet that contains the wanted password */
731
867
  
732
868
  if(debug){
733
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
734
 
            ip);
 
869
    fprintf(stderr, "Mandos plugin mandos-client: "
 
870
            "Retrieving OpenPGP encrypted password from %s\n", ip);
735
871
  }
736
872
  
737
873
  while(true){
738
874
    
739
875
    if(quit_now){
 
876
      errno = EINTR;
740
877
      goto mandos_end;
741
878
    }
742
879
    
743
880
    buffer_capacity = incbuffer(&buffer, buffer_length,
744
881
                                   buffer_capacity);
745
882
    if(buffer_capacity == 0){
746
 
      perror("incbuffer");
747
 
      retval = -1;
 
883
      int e = errno;
 
884
      perror_plus("incbuffer");
 
885
      errno = e;
748
886
      goto mandos_end;
749
887
    }
750
888
    
751
889
    if(quit_now){
 
890
      errno = EINTR;
752
891
      goto mandos_end;
753
892
    }
754
893
    
767
906
          ret = gnutls_handshake(session);
768
907
          
769
908
          if(quit_now){
 
909
            errno = EINTR;
770
910
            goto mandos_end;
771
911
          }
772
912
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
773
913
        if(ret < 0){
774
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
914
          fprintf(stderr, "Mandos plugin mandos-client: "
 
915
                  "*** GnuTLS Re-handshake failed ***\n");
775
916
          gnutls_perror(ret);
776
 
          retval = -1;
 
917
          errno = EPROTO;
777
918
          goto mandos_end;
778
919
        }
779
920
        break;
780
921
      default:
781
 
        fprintf(stderr, "Unknown error while reading data from"
 
922
        fprintf(stderr, "Mandos plugin mandos-client: "
 
923
                "Unknown error while reading data from"
782
924
                " encrypted session with Mandos server\n");
783
 
        retval = -1;
784
925
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
926
        errno = EIO;
785
927
        goto mandos_end;
786
928
      }
787
929
    } else {
790
932
  }
791
933
  
792
934
  if(debug){
793
 
    fprintf(stderr, "Closing TLS session\n");
794
 
  }
795
 
  
796
 
  if(quit_now){
797
 
    goto mandos_end;
798
 
  }
799
 
  
800
 
  gnutls_bye(session, GNUTLS_SHUT_RDWR);
801
 
  
802
 
  if(quit_now){
803
 
    goto mandos_end;
804
 
  }
 
935
    fprintf(stderr, "Mandos plugin mandos-client: "
 
936
            "Closing TLS session\n");
 
937
  }
 
938
  
 
939
  if(quit_now){
 
940
    errno = EINTR;
 
941
    goto mandos_end;
 
942
  }
 
943
  
 
944
  do {
 
945
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
 
946
    if(quit_now){
 
947
      errno = EINTR;
 
948
      goto mandos_end;
 
949
    }
 
950
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
805
951
  
806
952
  if(buffer_length > 0){
807
953
    ssize_t decrypted_buffer_size;
813
959
      written = 0;
814
960
      while(written < (size_t) decrypted_buffer_size){
815
961
        if(quit_now){
 
962
          errno = EINTR;
816
963
          goto mandos_end;
817
964
        }
818
965
        
820
967
                          (size_t)decrypted_buffer_size - written,
821
968
                          stdout);
822
969
        if(ret == 0 and ferror(stdout)){
 
970
          int e = errno;
823
971
          if(debug){
824
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
972
            fprintf(stderr, "Mandos plugin mandos-client: "
 
973
                    "Error writing encrypted data: %s\n",
825
974
                    strerror(errno));
826
975
          }
827
 
          retval = -1;
828
 
          break;
 
976
          errno = e;
 
977
          goto mandos_end;
829
978
        }
830
979
        written += (size_t)ret;
831
980
      }
832
 
      free(decrypted_buffer);
833
 
    } else {
834
 
      retval = -1;
 
981
      retval = 0;
835
982
    }
836
 
  } else {
837
 
    retval = -1;
838
983
  }
839
984
  
840
985
  /* Shutdown procedure */
841
986
  
842
987
 mandos_end:
843
 
  free(buffer);
844
 
  if(tcp_sd >= 0){
845
 
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
846
 
  }
847
 
  if(ret == -1){
848
 
    perror("close");
849
 
  }
850
 
  gnutls_deinit(session);
851
 
  if(quit_now){
852
 
    retval = -1;
 
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
    }
853
1007
  }
854
1008
  return retval;
855
1009
}
880
1034
  switch(event){
881
1035
  default:
882
1036
  case AVAHI_RESOLVER_FAILURE:
883
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
1037
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1038
            "(Avahi Resolver) Failed to resolve service '%s'"
884
1039
            " of type '%s' in domain '%s': %s\n", name, type, domain,
885
1040
            avahi_strerror(avahi_server_errno(mc.server)));
886
1041
    break;
890
1045
      char ip[AVAHI_ADDRESS_STR_MAX];
891
1046
      avahi_address_snprint(ip, sizeof(ip), address);
892
1047
      if(debug){
893
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1048
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1049
                "Mandos server \"%s\" found on %s (%s, %"
894
1050
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
895
1051
                ip, (intmax_t)interface, port);
896
1052
      }
898
1054
                                           avahi_proto_to_af(proto));
899
1055
      if(ret == 0){
900
1056
        avahi_simple_poll_quit(mc.simple_poll);
 
1057
      } else {
 
1058
        ret = add_server(ip, port, interface,
 
1059
                         avahi_proto_to_af(proto));
901
1060
      }
902
1061
    }
903
1062
  }
927
1086
  default:
928
1087
  case AVAHI_BROWSER_FAILURE:
929
1088
    
930
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1089
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1090
            "(Avahi browser) %s\n",
931
1091
            avahi_strerror(avahi_server_errno(mc.server)));
932
1092
    avahi_simple_poll_quit(mc.simple_poll);
933
1093
    return;
941
1101
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
942
1102
                                    name, type, domain, protocol, 0,
943
1103
                                    resolve_callback, NULL) == NULL)
944
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1104
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1105
              "Avahi: Failed to resolve service '%s': %s\n",
945
1106
              name, avahi_strerror(avahi_server_errno(mc.server)));
946
1107
    break;
947
1108
    
951
1112
  case AVAHI_BROWSER_ALL_FOR_NOW:
952
1113
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
953
1114
    if(debug){
954
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1115
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1116
              "No Mandos server found, still searching...\n");
955
1117
    }
956
1118
    break;
957
1119
  }
958
1120
}
959
1121
 
960
 
/* stop main loop after sigterm has been called */
 
1122
/* Signal handler that stops main loop after SIGTERM */
961
1123
static void handle_sigterm(int sig){
962
1124
  if(quit_now){
963
1125
    return;
965
1127
  quit_now = 1;
966
1128
  signal_received = sig;
967
1129
  int old_errno = errno;
 
1130
  /* set main loop to exit */
968
1131
  if(mc.simple_poll != NULL){
969
1132
    avahi_simple_poll_quit(mc.simple_poll);
970
1133
  }
971
1134
  errno = old_errno;
972
1135
}
973
1136
 
 
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
 
974
1407
int main(int argc, char *argv[]){
975
1408
  AvahiSServiceBrowser *sb = NULL;
976
1409
  int error;
978
1411
  intmax_t tmpmax;
979
1412
  char *tmp;
980
1413
  int exitcode = EXIT_SUCCESS;
981
 
  const char *interface = "eth0";
 
1414
  const char *interface = "";
982
1415
  struct ifreq network;
983
1416
  int sd = -1;
984
1417
  bool take_down_interface = false;
985
1418
  uid_t uid;
986
1419
  gid_t gid;
987
 
  char *connect_to = NULL;
988
1420
  char tempdir[] = "/tmp/mandosXXXXXX";
989
1421
  bool tempdir_created = false;
990
1422
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
994
1426
  bool gnutls_initialized = false;
995
1427
  bool gpgme_initialized = false;
996
1428
  float delay = 2.5f;
 
1429
  double retry_interval = 10; /* 10s between trying a server and
 
1430
                                 retrying the same server again */
997
1431
  
998
 
  struct sigaction old_sigterm_action;
 
1432
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
999
1433
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1000
1434
  
 
1435
  uid = getuid();
 
1436
  gid = getgid();
 
1437
  
 
1438
  /* Lower any group privileges we might have, just to be safe */
 
1439
  errno = 0;
 
1440
  ret = setgid(gid);
 
1441
  if(ret == -1){
 
1442
    perror_plus("setgid");
 
1443
  }
 
1444
  
 
1445
  /* Lower user privileges (temporarily) */
 
1446
  errno = 0;
 
1447
  ret = seteuid(uid);
 
1448
  if(ret == -1){
 
1449
    perror_plus("seteuid");
 
1450
  }
 
1451
  
 
1452
  if(quit_now){
 
1453
    goto end;
 
1454
  }
 
1455
  
1001
1456
  {
1002
1457
    struct argp_option options[] = {
1003
1458
      { .name = "debug", .key = 128,
1032
1487
        .arg = "SECONDS",
1033
1488
        .doc = "Maximum delay to wait for interface startup",
1034
1489
        .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 },
1035
1507
      { .name = NULL }
1036
1508
    };
1037
1509
    
1038
1510
    error_t parse_opt(int key, char *arg,
1039
1511
                      struct argp_state *state){
 
1512
      errno = 0;
1040
1513
      switch(key){
1041
1514
      case 128:                 /* --debug */
1042
1515
        debug = true;
1058
1531
        tmpmax = strtoimax(arg, &tmp, 10);
1059
1532
        if(errno != 0 or tmp == arg or *tmp != '\0'
1060
1533
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1061
 
          fprintf(stderr, "Bad number of DH bits\n");
1062
 
          exit(EXIT_FAILURE);
 
1534
          argp_error(state, "Bad number of DH bits");
1063
1535
        }
1064
1536
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1065
1537
        break;
1070
1542
        errno = 0;
1071
1543
        delay = strtof(arg, &tmp);
1072
1544
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1073
 
          fprintf(stderr, "Bad delay\n");
1074
 
          exit(EXIT_FAILURE);
1075
 
        }
1076
 
        break;
1077
 
      case ARGP_KEY_ARG:
1078
 
        argp_usage(state);
1079
 
      case ARGP_KEY_END:
 
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);
1080
1573
        break;
1081
1574
      default:
1082
1575
        return ARGP_ERR_UNKNOWN;
1083
1576
      }
1084
 
      return 0;
 
1577
      return errno;
1085
1578
    }
1086
1579
    
1087
1580
    struct argp argp = { .options = options, .parser = parse_opt,
1088
1581
                         .args_doc = "",
1089
1582
                         .doc = "Mandos client -- Get and decrypt"
1090
1583
                         " passwords from a Mandos server" };
1091
 
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
1092
 
    if(ret == ARGP_ERR_UNKNOWN){
1093
 
      fprintf(stderr, "Unknown error while parsing arguments\n");
1094
 
      exitcode = EXIT_FAILURE;
1095
 
      goto end;
 
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);
1096
1752
    }
1097
1753
  }
1098
1754
  
1100
1756
    avahi_set_log_function(empty_log);
1101
1757
  }
1102
1758
  
 
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
  
1103
1793
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1104
1794
     from the signal handler */
1105
1795
  /* Initialize the pseudo-RNG for Avahi */
1106
1796
  srand((unsigned int) time(NULL));
1107
1797
  mc.simple_poll = avahi_simple_poll_new();
1108
1798
  if(mc.simple_poll == NULL){
1109
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1110
 
    exitcode = EXIT_FAILURE;
 
1799
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1800
            "Avahi: Failed to create simple poll object.\n");
 
1801
    exitcode = EX_UNAVAILABLE;
1111
1802
    goto end;
1112
1803
  }
1113
1804
  
1114
1805
  sigemptyset(&sigterm_action.sa_mask);
1115
1806
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1116
1807
  if(ret == -1){
1117
 
    perror("sigaddset");
1118
 
    exitcode = EXIT_FAILURE;
 
1808
    perror_plus("sigaddset");
 
1809
    exitcode = EX_OSERR;
1119
1810
    goto end;
1120
1811
  }
1121
1812
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1122
1813
  if(ret == -1){
1123
 
    perror("sigaddset");
1124
 
    exitcode = EXIT_FAILURE;
 
1814
    perror_plus("sigaddset");
 
1815
    exitcode = EX_OSERR;
1125
1816
    goto end;
1126
1817
  }
1127
1818
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1128
1819
  if(ret == -1){
1129
 
    perror("sigaddset");
1130
 
    exitcode = EXIT_FAILURE;
 
1820
    perror_plus("sigaddset");
 
1821
    exitcode = EX_OSERR;
1131
1822
    goto end;
1132
1823
  }
1133
1824
  /* Need to check if the handler is SIG_IGN before handling:
1136
1827
  */
1137
1828
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1138
1829
  if(ret == -1){
1139
 
    perror("sigaction");
1140
 
    return EXIT_FAILURE;
 
1830
    perror_plus("sigaction");
 
1831
    return EX_OSERR;
1141
1832
  }
1142
1833
  if(old_sigterm_action.sa_handler != SIG_IGN){
1143
1834
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1144
1835
    if(ret == -1){
1145
 
      perror("sigaction");
1146
 
      exitcode = EXIT_FAILURE;
 
1836
      perror_plus("sigaction");
 
1837
      exitcode = EX_OSERR;
1147
1838
      goto end;
1148
1839
    }
1149
1840
  }
1150
1841
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1151
1842
  if(ret == -1){
1152
 
    perror("sigaction");
1153
 
    return EXIT_FAILURE;
 
1843
    perror_plus("sigaction");
 
1844
    return EX_OSERR;
1154
1845
  }
1155
1846
  if(old_sigterm_action.sa_handler != SIG_IGN){
1156
1847
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1157
1848
    if(ret == -1){
1158
 
      perror("sigaction");
1159
 
      exitcode = EXIT_FAILURE;
 
1849
      perror_plus("sigaction");
 
1850
      exitcode = EX_OSERR;
1160
1851
      goto end;
1161
1852
    }
1162
1853
  }
1163
1854
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1164
1855
  if(ret == -1){
1165
 
    perror("sigaction");
1166
 
    return EXIT_FAILURE;
 
1856
    perror_plus("sigaction");
 
1857
    return EX_OSERR;
1167
1858
  }
1168
1859
  if(old_sigterm_action.sa_handler != SIG_IGN){
1169
1860
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1170
1861
    if(ret == -1){
1171
 
      perror("sigaction");
1172
 
      exitcode = EXIT_FAILURE;
 
1862
      perror_plus("sigaction");
 
1863
      exitcode = EX_OSERR;
1173
1864
      goto end;
1174
1865
    }
1175
1866
  }
1176
1867
  
1177
1868
  /* If the interface is down, bring it up */
1178
 
  if(interface[0] != '\0'){
 
1869
  if(strcmp(interface, "none") != 0){
1179
1870
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1180
1871
    if(if_index == 0){
1181
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1182
 
      exitcode = EXIT_FAILURE;
 
1872
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1873
              "No such interface: \"%s\"\n", interface);
 
1874
      exitcode = EX_UNAVAILABLE;
1183
1875
      goto end;
1184
1876
    }
1185
1877
    
1187
1879
      goto end;
1188
1880
    }
1189
1881
    
 
1882
    /* Re-raise priviliges */
 
1883
    errno = 0;
 
1884
    ret = seteuid(0);
 
1885
    if(ret == -1){
 
1886
      perror_plus("seteuid");
 
1887
    }
 
1888
    
1190
1889
#ifdef __linux__
1191
1890
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1192
 
       messages to mess up the prompt */
 
1891
       messages about the network interface to mess up the prompt */
1193
1892
    ret = klogctl(8, NULL, 5);
1194
1893
    bool restore_loglevel = true;
1195
1894
    if(ret == -1){
1196
1895
      restore_loglevel = false;
1197
 
      perror("klogctl");
 
1896
      perror_plus("klogctl");
1198
1897
    }
1199
1898
#endif  /* __linux__ */
1200
1899
    
1201
1900
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1202
1901
    if(sd < 0){
1203
 
      perror("socket");
1204
 
      exitcode = EXIT_FAILURE;
 
1902
      perror_plus("socket");
 
1903
      exitcode = EX_OSERR;
1205
1904
#ifdef __linux__
1206
1905
      if(restore_loglevel){
1207
1906
        ret = klogctl(7, NULL, 0);
1208
1907
        if(ret == -1){
1209
 
          perror("klogctl");
 
1908
          perror_plus("klogctl");
1210
1909
        }
1211
1910
      }
1212
1911
#endif  /* __linux__ */
 
1912
      /* Lower privileges */
 
1913
      errno = 0;
 
1914
      ret = seteuid(uid);
 
1915
      if(ret == -1){
 
1916
        perror_plus("seteuid");
 
1917
      }
1213
1918
      goto end;
1214
1919
    }
1215
1920
    strcpy(network.ifr_name, interface);
1216
1921
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1217
1922
    if(ret == -1){
1218
 
      perror("ioctl SIOCGIFFLAGS");
 
1923
      perror_plus("ioctl SIOCGIFFLAGS");
1219
1924
#ifdef __linux__
1220
1925
      if(restore_loglevel){
1221
1926
        ret = klogctl(7, NULL, 0);
1222
1927
        if(ret == -1){
1223
 
          perror("klogctl");
 
1928
          perror_plus("klogctl");
1224
1929
        }
1225
1930
      }
1226
1931
#endif  /* __linux__ */
1227
 
      exitcode = EXIT_FAILURE;
 
1932
      exitcode = EX_OSERR;
 
1933
      /* Lower privileges */
 
1934
      errno = 0;
 
1935
      ret = seteuid(uid);
 
1936
      if(ret == -1){
 
1937
        perror_plus("seteuid");
 
1938
      }
1228
1939
      goto end;
1229
1940
    }
1230
1941
    if((network.ifr_flags & IFF_UP) == 0){
1233
1944
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1234
1945
      if(ret == -1){
1235
1946
        take_down_interface = false;
1236
 
        perror("ioctl SIOCSIFFLAGS");
1237
 
        exitcode = EXIT_FAILURE;
 
1947
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1948
        exitcode = EX_OSERR;
1238
1949
#ifdef __linux__
1239
1950
        if(restore_loglevel){
1240
1951
          ret = klogctl(7, NULL, 0);
1241
1952
          if(ret == -1){
1242
 
            perror("klogctl");
 
1953
            perror_plus("klogctl");
1243
1954
          }
1244
1955
        }
1245
1956
#endif  /* __linux__ */
 
1957
        /* Lower privileges */
 
1958
        errno = 0;
 
1959
        ret = seteuid(uid);
 
1960
        if(ret == -1){
 
1961
          perror_plus("seteuid");
 
1962
        }
1246
1963
        goto end;
1247
1964
      }
1248
1965
    }
1249
 
    /* sleep checking until interface is running */
 
1966
    /* Sleep checking until interface is running.
 
1967
       Check every 0.25s, up to total time of delay */
1250
1968
    for(int i=0; i < delay * 4; i++){
1251
1969
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1252
1970
      if(ret == -1){
1253
 
        perror("ioctl SIOCGIFFLAGS");
 
1971
        perror_plus("ioctl SIOCGIFFLAGS");
1254
1972
      } else if(network.ifr_flags & IFF_RUNNING){
1255
1973
        break;
1256
1974
      }
1257
1975
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1258
1976
      ret = nanosleep(&sleeptime, NULL);
1259
1977
      if(ret == -1 and errno != EINTR){
1260
 
        perror("nanosleep");
 
1978
        perror_plus("nanosleep");
1261
1979
      }
1262
1980
    }
1263
1981
    if(not take_down_interface){
1264
1982
      /* We won't need the socket anymore */
1265
1983
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1266
1984
      if(ret == -1){
1267
 
        perror("close");
 
1985
        perror_plus("close");
1268
1986
      }
1269
1987
    }
1270
1988
#ifdef __linux__
1272
1990
      /* Restores kernel loglevel to default */
1273
1991
      ret = klogctl(7, NULL, 0);
1274
1992
      if(ret == -1){
1275
 
        perror("klogctl");
 
1993
        perror_plus("klogctl");
1276
1994
      }
1277
1995
    }
1278
1996
#endif  /* __linux__ */
1279
 
  }
1280
 
  
1281
 
  if(quit_now){
1282
 
    goto end;
1283
 
  }
1284
 
  
1285
 
  uid = getuid();
1286
 
  gid = getgid();
1287
 
  
1288
 
  errno = 0;
1289
 
  setgid(gid);
1290
 
  if(ret == -1){
1291
 
    perror("setgid");
1292
 
  }
1293
 
  
1294
 
  ret = setuid(uid);
1295
 
  if(ret == -1){
1296
 
    perror("setuid");
 
1997
    /* Lower privileges */
 
1998
    errno = 0;
 
1999
    if(take_down_interface){
 
2000
      /* Lower privileges */
 
2001
      ret = seteuid(uid);
 
2002
      if(ret == -1){
 
2003
        perror_plus("seteuid");
 
2004
      }
 
2005
    } else {
 
2006
      /* Lower privileges permanently */
 
2007
      ret = setuid(uid);
 
2008
      if(ret == -1){
 
2009
        perror_plus("setuid");
 
2010
      }
 
2011
    }
1297
2012
  }
1298
2013
  
1299
2014
  if(quit_now){
1302
2017
  
1303
2018
  ret = init_gnutls_global(pubkey, seckey);
1304
2019
  if(ret == -1){
1305
 
    fprintf(stderr, "init_gnutls_global failed\n");
1306
 
    exitcode = EXIT_FAILURE;
 
2020
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2021
            "init_gnutls_global failed\n");
 
2022
    exitcode = EX_UNAVAILABLE;
1307
2023
    goto end;
1308
2024
  } else {
1309
2025
    gnutls_initialized = true;
1313
2029
    goto end;
1314
2030
  }
1315
2031
  
 
2032
  if(mkdtemp(tempdir) == NULL){
 
2033
    perror_plus("mkdtemp");
 
2034
    goto end;
 
2035
  }
1316
2036
  tempdir_created = true;
1317
 
  if(mkdtemp(tempdir) == NULL){
1318
 
    tempdir_created = false;
1319
 
    perror("mkdtemp");
1320
 
    goto end;
1321
 
  }
1322
2037
  
1323
2038
  if(quit_now){
1324
2039
    goto end;
1325
2040
  }
1326
2041
  
1327
2042
  if(not init_gpgme(pubkey, seckey, tempdir)){
1328
 
    fprintf(stderr, "init_gpgme failed\n");
1329
 
    exitcode = EXIT_FAILURE;
 
2043
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2044
            "init_gpgme failed\n");
 
2045
    exitcode = EX_UNAVAILABLE;
1330
2046
    goto end;
1331
2047
  } else {
1332
2048
    gpgme_initialized = true;
1341
2057
    /* (Mainly meant for debugging) */
1342
2058
    char *address = strrchr(connect_to, ':');
1343
2059
    if(address == NULL){
1344
 
      fprintf(stderr, "No colon in address\n");
1345
 
      exitcode = EXIT_FAILURE;
 
2060
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2061
              "No colon in address\n");
 
2062
      exitcode = EX_USAGE;
1346
2063
      goto end;
1347
2064
    }
1348
2065
    
1355
2072
    tmpmax = strtoimax(address+1, &tmp, 10);
1356
2073
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1357
2074
       or tmpmax != (uint16_t)tmpmax){
1358
 
      fprintf(stderr, "Bad port number\n");
1359
 
      exitcode = EXIT_FAILURE;
 
2075
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2076
              "Bad port number\n");
 
2077
      exitcode = EX_USAGE;
1360
2078
      goto end;
1361
2079
    }
1362
2080
  
1366
2084
    
1367
2085
    port = (uint16_t)tmpmax;
1368
2086
    *address = '\0';
1369
 
    address = connect_to;
1370
2087
    /* Colon in address indicates IPv6 */
1371
2088
    int af;
1372
 
    if(strchr(address, ':') != NULL){
 
2089
    if(strchr(connect_to, ':') != NULL){
1373
2090
      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
        }
1374
2097
    } else {
1375
2098
      af = AF_INET;
1376
2099
    }
 
2100
    address = connect_to;
1377
2101
    
1378
2102
    if(quit_now){
1379
2103
      goto end;
1380
2104
    }
1381
2105
    
1382
 
    ret = start_mandos_communication(address, port, if_index, af);
1383
 
    if(ret < 0){
1384
 
      exitcode = EXIT_FAILURE;
1385
 
    } else {
 
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){
1386
2119
      exitcode = EXIT_SUCCESS;
1387
2120
    }
 
2121
    
1388
2122
    goto end;
1389
2123
  }
1390
2124
  
1412
2146
  
1413
2147
  /* Check if creating the Avahi server object succeeded */
1414
2148
  if(mc.server == NULL){
1415
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2149
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2150
            "Failed to create Avahi server: %s\n",
1416
2151
            avahi_strerror(error));
1417
 
    exitcode = EXIT_FAILURE;
 
2152
    exitcode = EX_UNAVAILABLE;
1418
2153
    goto end;
1419
2154
  }
1420
2155
  
1427
2162
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1428
2163
                                   NULL, 0, browse_callback, NULL);
1429
2164
  if(sb == NULL){
1430
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2165
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2166
            "Failed to create service browser: %s\n",
1431
2167
            avahi_strerror(avahi_server_errno(mc.server)));
1432
 
    exitcode = EXIT_FAILURE;
 
2168
    exitcode = EX_UNAVAILABLE;
1433
2169
    goto end;
1434
2170
  }
1435
2171
  
1440
2176
  /* Run the main loop */
1441
2177
  
1442
2178
  if(debug){
1443
 
    fprintf(stderr, "Starting Avahi loop search\n");
1444
 
  }
1445
 
  
1446
 
  avahi_simple_poll_loop(mc.simple_poll);
 
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
  }
1447
2190
  
1448
2191
 end:
1449
2192
  
1450
2193
  if(debug){
1451
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2194
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2195
            "%s exiting\n", argv[0]);
1452
2196
  }
1453
2197
  
1454
2198
  /* Cleanup things */
1470
2214
  if(gpgme_initialized){
1471
2215
    gpgme_release(mc.ctx);
1472
2216
  }
 
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  */
1473
2230
  
1474
2231
  /* Take down the network interface */
1475
2232
  if(take_down_interface){
1476
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2233
    /* Re-raise priviliges */
 
2234
    errno = 0;
 
2235
    ret = seteuid(0);
1477
2236
    if(ret == -1){
1478
 
      perror("ioctl SIOCGIFFLAGS");
1479
 
    } else if(network.ifr_flags & IFF_UP) {
1480
 
      network.ifr_flags &= ~IFF_UP; /* clear flag */
1481
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1482
 
      if(ret == -1){
1483
 
        perror("ioctl SIOCSIFFLAGS");
1484
 
      }
 
2237
      perror_plus("seteuid");
1485
2238
    }
1486
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1487
 
    if(ret == -1){
1488
 
      perror("close");
 
2239
    if(geteuid() == 0){
 
2240
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
2241
      if(ret == -1){
 
2242
        perror_plus("ioctl SIOCGIFFLAGS");
 
2243
      } else if(network.ifr_flags & IFF_UP){
 
2244
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
2245
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
2246
        if(ret == -1){
 
2247
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
2248
        }
 
2249
      }
 
2250
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
2251
      if(ret == -1){
 
2252
        perror_plus("close");
 
2253
      }
 
2254
      /* Lower privileges permanently */
 
2255
      errno = 0;
 
2256
      ret = setuid(uid);
 
2257
      if(ret == -1){
 
2258
        perror_plus("setuid");
 
2259
      }
1489
2260
    }
1490
2261
  }
1491
2262
  
1492
 
  /* Removes the temp directory used by GPGME */
 
2263
  /* Removes the GPGME temp directory and all files inside */
1493
2264
  if(tempdir_created){
1494
 
    DIR *d;
1495
 
    struct dirent *direntry;
1496
 
    d = opendir(tempdir);
1497
 
    if(d == NULL){
1498
 
      if(errno != ENOENT){
1499
 
        perror("opendir");
1500
 
      }
1501
 
    } else {
1502
 
      while(true){
1503
 
        direntry = readdir(d);
1504
 
        if(direntry == NULL){
1505
 
          break;
1506
 
        }
1507
 
        /* Skip "." and ".." */
1508
 
        if(direntry->d_name[0] == '.'
1509
 
           and (direntry->d_name[1] == '\0'
1510
 
                or (direntry->d_name[1] == '.'
1511
 
                    and direntry->d_name[2] == '\0'))){
1512
 
          continue;
1513
 
        }
 
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];
1514
2272
        char *fullname = NULL;
1515
2273
        ret = asprintf(&fullname, "%s/%s", tempdir,
1516
2274
                       direntry->d_name);
1517
2275
        if(ret < 0){
1518
 
          perror("asprintf");
 
2276
          perror_plus("asprintf");
1519
2277
          continue;
1520
2278
        }
1521
2279
        ret = remove(fullname);
1522
2280
        if(ret == -1){
1523
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1524
 
                  strerror(errno));
 
2281
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2282
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
1525
2283
        }
1526
2284
        free(fullname);
1527
2285
      }
1528
 
      closedir(d);
 
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");
1529
2292
    }
1530
2293
    ret = rmdir(tempdir);
1531
2294
    if(ret == -1 and errno != ENOENT){
1532
 
      perror("rmdir");
 
2295
      perror_plus("rmdir");
1533
2296
    }
1534
2297
  }
1535
2298
  
1536
2299
  if(quit_now){
1537
2300
    sigemptyset(&old_sigterm_action.sa_mask);
1538
2301
    old_sigterm_action.sa_handler = SIG_DFL;
1539
 
    ret = sigaction(signal_received, &old_sigterm_action, NULL);
 
2302
    ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received,
 
2303
                                            &old_sigterm_action,
 
2304
                                            NULL));
1540
2305
    if(ret == -1){
1541
 
      perror("sigaction");
1542
 
    }
1543
 
    raise(signal_received);
 
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());
1544
2316
  }
1545
2317
  
1546
2318
  return exitcode;