/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: Björn Påhlsson
  • Date: 2011-06-23 22:27:15 UTC
  • mto: This revision was merged to the branch mainline in revision 485.
  • Revision ID: belorn@fukt.bsnet.se-20110623222715-q5wro9ma9iyjl367
* Makefile (CFLAGS): Added "-lrt" to include real time library.
* plugins.d/mandos-client.c: use scandir(3) instead of readdir(3)
                             Prefix all debug output with "Mandos plugin " + program_invocation_short_name
                             Retry servers that failed to provide password.
                             New option --retry SECONDS that sets the interval between rechecking.
                             --retry also controls how often it retries a server when using --connect.
* plugins.d/splashy.c:  Prefix all debug output with "Mandos plugin " + program_invocation_short_name
* plugins.d/usplash.c: --||--
* plugins.d/askpass-fifo.c: --||--
* plugins.d/password-prompt.c: --||--
* plugins.d/plymouth.c: --||--
* mandos: Lower logger level from warning to info on failed client requests because client was disabled or unknown fingerprint.
* plugins.d/plymouth.c (get_pid): bug fix. Was not calling free on direntries. 

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
 
65
#include <errno.h>              /* perror(), errno, program_invocation_short_name */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
75
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
85
84
                                   raise() */
86
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
87
 
91
88
#ifdef __linux__
92
89
#include <sys/klog.h>           /* klogctl() */
110
107
                                   init_gnutls_session(),
111
108
                                   GNUTLS_* */
112
109
#include <gnutls/openpgp.h>
113
 
                         /* gnutls_certificate_set_openpgp_key_file(),
114
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
110
                          /* gnutls_certificate_set_openpgp_key_file(),
 
111
                                   GNUTLS_OPENPGP_FMT_BASE64 */
115
112
 
116
113
/* GPGME */
117
114
#include <gpgme.h>              /* All GPGME types, constants and
125
122
#define PATHDIR "/conf/conf.d/mandos"
126
123
#define SECKEY "seckey.txt"
127
124
#define PUBKEY "pubkey.txt"
128
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
129
125
 
130
126
bool debug = false;
131
127
static const char mandos_protocol_version[] = "1";
132
128
const char *argp_program_version = "mandos-client " VERSION;
133
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
134
130
static const char sys_class_net[] = "/sys/class/net";
135
131
char *connect_to = NULL;
136
 
const char *hookdir = HOOKDIR;
137
132
 
138
 
/* Doubly linked list that need to be circularly linked when used */
 
133
/* Doubly linked list that need to be circular linked when ever used */
139
134
typedef struct server{
140
135
  const char *ip;
141
136
  uint16_t port;
161
156
/* global context so signal handler can reach it*/
162
157
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
158
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
159
                      ":!CTYPE-X.509:+CTYPE-OPENPGP", .current_server = NULL };
166
160
 
167
161
sig_atomic_t quit_now = 0;
168
162
int signal_received = 0;
169
163
 
170
164
/* Function to use when printing errors */
171
165
void perror_plus(const char *print_text){
172
 
  fprintf(stderr, "Mandos plugin %s: ",
173
 
          program_invocation_short_name);
 
166
  fprintf(stderr, "Mandos plugin %s: ", program_invocation_short_name);
174
167
  perror(print_text);
175
168
}
176
169
 
180
173
 * "buffer_length" is how much is already used.
181
174
 */
182
175
size_t incbuffer(char **buffer, size_t buffer_length,
183
 
                 size_t buffer_capacity){
 
176
                  size_t buffer_capacity){
184
177
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
185
178
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
179
    if(buffer == NULL){
191
184
  return buffer_capacity;
192
185
}
193
186
 
194
 
/* Add server to set of servers to retry periodically */
195
 
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
196
 
               int af){
 
187
int add_server(const char *ip, uint16_t port,
 
188
                 AvahiIfIndex if_index,
 
189
                 int af){
197
190
  int ret;
198
191
  server *new_server = malloc(sizeof(server));
199
192
  if(new_server == NULL){
201
194
    return -1;
202
195
  }
203
196
  *new_server = (server){ .ip = strdup(ip),
204
 
                          .port = port,
205
 
                          .if_index = if_index,
206
 
                          .af = af };
 
197
                         .port = port,
 
198
                         .if_index = if_index,
 
199
                         .af = af };
207
200
  if(new_server->ip == NULL){
208
201
    perror_plus("strdup");
209
 
    return -1;
 
202
    return -1;    
210
203
  }
211
 
  /* Special case of first server */
 
204
  /* uniqe case of first server */
212
205
  if (mc.current_server == NULL){
213
206
    new_server->next = new_server;
214
207
    new_server->prev = new_server;
215
208
    mc.current_server = new_server;
216
 
  /* Place the new server last in the list */
 
209
  /* Placing the new server last in the list */
217
210
  } else {
218
211
    new_server->next = mc.current_server;
219
212
    new_server->prev = mc.current_server->prev;
231
224
/* 
232
225
 * Initialize GPGME.
233
226
 */
234
 
static bool init_gpgme(const char *seckey, const char *pubkey,
235
 
                       const char *tempdir){
 
227
static bool init_gpgme(const char *seckey,
 
228
                       const char *pubkey, const char *tempdir){
236
229
  gpgme_error_t rc;
237
230
  gpgme_engine_info_t engine_info;
238
231
  
253
246
    
254
247
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
255
248
    if(rc != GPG_ERR_NO_ERROR){
256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
257
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
249
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
258
250
              gpgme_strsource(rc), gpgme_strerror(rc));
259
251
      return false;
260
252
    }
261
253
    
262
254
    rc = gpgme_op_import(mc.ctx, pgp_data);
263
255
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_op_import: %s: %s\n",
 
256
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
266
257
              gpgme_strsource(rc), gpgme_strerror(rc));
267
258
      return false;
268
259
    }
276
267
  }
277
268
  
278
269
  if(debug){
279
 
    fprintf(stderr, "Mandos plugin mandos-client: "
280
 
            "Initializing GPGME\n");
 
270
    fprintf(stderr, "Initializing GPGME\n");
281
271
  }
282
272
  
283
273
  /* Init GPGME */
284
274
  gpgme_check_version(NULL);
285
275
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
286
276
  if(rc != GPG_ERR_NO_ERROR){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "bad gpgme_engine_check_version: %s: %s\n",
 
277
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
289
278
            gpgme_strsource(rc), gpgme_strerror(rc));
290
279
    return false;
291
280
  }
292
281
  
293
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
282
    /* Set GPGME home directory for the OpenPGP engine only */
294
283
  rc = gpgme_get_engine_info(&engine_info);
295
284
  if(rc != GPG_ERR_NO_ERROR){
296
 
    fprintf(stderr, "Mandos plugin mandos-client: "
297
 
            "bad gpgme_get_engine_info: %s: %s\n",
 
285
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
298
286
            gpgme_strsource(rc), gpgme_strerror(rc));
299
287
    return false;
300
288
  }
307
295
    engine_info = engine_info->next;
308
296
  }
309
297
  if(engine_info == NULL){
310
 
    fprintf(stderr, "Mandos plugin mandos-client: "
311
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
298
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
312
299
    return false;
313
300
  }
314
301
  
315
302
  /* Create new GPGME "context" */
316
303
  rc = gpgme_new(&(mc.ctx));
317
304
  if(rc != GPG_ERR_NO_ERROR){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
320
 
            gpgme_strerror(rc));
 
305
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
306
            gpgme_strsource(rc), gpgme_strerror(rc));
321
307
    return false;
322
308
  }
323
309
  
342
328
  ssize_t plaintext_length = 0;
343
329
  
344
330
  if(debug){
345
 
    fprintf(stderr, "Mandos plugin mandos-client: "
346
 
            "Trying to decrypt OpenPGP data\n");
 
331
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
347
332
  }
348
333
  
349
334
  /* Create new GPGME data buffer from memory cryptotext */
350
335
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
351
336
                               0);
352
337
  if(rc != GPG_ERR_NO_ERROR){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
338
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
355
339
            gpgme_strsource(rc), gpgme_strerror(rc));
356
340
    return -1;
357
341
  }
359
343
  /* Create new empty GPGME data buffer for the plaintext */
360
344
  rc = gpgme_data_new(&dh_plain);
361
345
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf(stderr, "Mandos plugin mandos-client: "
363
 
            "bad gpgme_data_new: %s: %s\n",
 
346
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
364
347
            gpgme_strsource(rc), gpgme_strerror(rc));
365
348
    gpgme_data_release(dh_crypto);
366
349
    return -1;
370
353
     data buffer */
371
354
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
372
355
  if(rc != GPG_ERR_NO_ERROR){
373
 
    fprintf(stderr, "Mandos plugin mandos-client: "
374
 
            "bad gpgme_op_decrypt: %s: %s\n",
 
356
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
375
357
            gpgme_strsource(rc), gpgme_strerror(rc));
376
358
    plaintext_length = -1;
377
359
    if(debug){
378
360
      gpgme_decrypt_result_t result;
379
361
      result = gpgme_op_decrypt_result(mc.ctx);
380
362
      if(result == NULL){
381
 
        fprintf(stderr, "Mandos plugin mandos-client: "
382
 
                "gpgme_op_decrypt_result failed\n");
 
363
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
383
364
      } else {
384
 
        fprintf(stderr, "Mandos plugin mandos-client: "
385
 
                "Unsupported algorithm: %s\n",
 
365
        fprintf(stderr, "Unsupported algorithm: %s\n",
386
366
                result->unsupported_algorithm);
387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
388
 
                "Wrong key usage: %u\n",
 
367
        fprintf(stderr, "Wrong key usage: %u\n",
389
368
                result->wrong_key_usage);
390
369
        if(result->file_name != NULL){
391
 
          fprintf(stderr, "Mandos plugin mandos-client: "
392
 
                  "File name: %s\n", result->file_name);
 
370
          fprintf(stderr, "File name: %s\n", result->file_name);
393
371
        }
394
372
        gpgme_recipient_t recipient;
395
373
        recipient = result->recipients;
396
374
        while(recipient != NULL){
397
 
          fprintf(stderr, "Mandos plugin mandos-client: "
398
 
                  "Public key algorithm: %s\n",
 
375
          fprintf(stderr, "Public key algorithm: %s\n",
399
376
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
400
 
          fprintf(stderr, "Mandos plugin mandos-client: "
401
 
                  "Key ID: %s\n", recipient->keyid);
402
 
          fprintf(stderr, "Mandos plugin mandos-client: "
403
 
                  "Secret key available: %s\n",
 
377
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
378
          fprintf(stderr, "Secret key available: %s\n",
404
379
                  recipient->status == GPG_ERR_NO_SECKEY
405
380
                  ? "No" : "Yes");
406
381
          recipient = recipient->next;
411
386
  }
412
387
  
413
388
  if(debug){
414
 
    fprintf(stderr, "Mandos plugin mandos-client: "
415
 
            "Decryption of OpenPGP data succeeded\n");
 
389
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
416
390
  }
417
391
  
418
392
  /* Seek back to the beginning of the GPGME plaintext data buffer */
425
399
  *plaintext = NULL;
426
400
  while(true){
427
401
    plaintext_capacity = incbuffer(plaintext,
428
 
                                   (size_t)plaintext_length,
429
 
                                   plaintext_capacity);
 
402
                                      (size_t)plaintext_length,
 
403
                                      plaintext_capacity);
430
404
    if(plaintext_capacity == 0){
431
 
      perror_plus("incbuffer");
432
 
      plaintext_length = -1;
433
 
      goto decrypt_end;
 
405
        perror_plus("incbuffer");
 
406
        plaintext_length = -1;
 
407
        goto decrypt_end;
434
408
    }
435
409
    
436
410
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
449
423
  }
450
424
  
451
425
  if(debug){
452
 
    fprintf(stderr, "Mandos plugin mandos-client: "
453
 
            "Decrypted password is: ");
 
426
    fprintf(stderr, "Decrypted password is: ");
454
427
    for(ssize_t i = 0; i < plaintext_length; i++){
455
428
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
456
429
    }
478
451
/* GnuTLS log function callback */
479
452
static void debuggnutls(__attribute__((unused)) int level,
480
453
                        const char* string){
481
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
454
  fprintf(stderr, "GnuTLS: %s", string);
482
455
}
483
456
 
484
457
static int init_gnutls_global(const char *pubkeyfilename,
486
459
  int ret;
487
460
  
488
461
  if(debug){
489
 
    fprintf(stderr, "Mandos plugin mandos-client: "
490
 
            "Initializing GnuTLS\n");
 
462
    fprintf(stderr, "Initializing GnuTLS\n");
491
463
  }
492
464
  
493
465
  ret = gnutls_global_init();
494
466
  if(ret != GNUTLS_E_SUCCESS){
495
 
    fprintf(stderr, "Mandos plugin mandos-client: "
496
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
467
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
468
            safer_gnutls_strerror(ret));
497
469
    return -1;
498
470
  }
499
471
  
506
478
  }
507
479
  
508
480
  /* OpenPGP credentials */
509
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
481
  gnutls_certificate_allocate_credentials(&mc.cred);
510
482
  if(ret != GNUTLS_E_SUCCESS){
511
 
    fprintf(stderr, "Mandos plugin mandos-client: "
512
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
483
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
484
                                                    from
 
485
                                                    -Wunreachable-code
 
486
                                                 */
 
487
            safer_gnutls_strerror(ret));
513
488
    gnutls_global_deinit();
514
489
    return -1;
515
490
  }
516
491
  
517
492
  if(debug){
518
 
    fprintf(stderr, "Mandos plugin mandos-client: "
519
 
            "Attempting to use OpenPGP public key %s and"
 
493
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
520
494
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
521
495
            seckeyfilename);
522
496
  }
526
500
     GNUTLS_OPENPGP_FMT_BASE64);
527
501
  if(ret != GNUTLS_E_SUCCESS){
528
502
    fprintf(stderr,
529
 
            "Mandos plugin mandos-client: "
530
503
            "Error[%d] while reading the OpenPGP key pair ('%s',"
531
504
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
532
 
    fprintf(stderr, "Mandos plugin mandos-client: "
533
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
505
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
506
            safer_gnutls_strerror(ret));
534
507
    goto globalfail;
535
508
  }
536
509
  
537
510
  /* GnuTLS server initialization */
538
511
  ret = gnutls_dh_params_init(&mc.dh_params);
539
512
  if(ret != GNUTLS_E_SUCCESS){
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "Error in GnuTLS DH parameter initialization:"
 
513
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
542
514
            " %s\n", safer_gnutls_strerror(ret));
543
515
    goto globalfail;
544
516
  }
545
517
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
546
518
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Mandos plugin mandos-client: "
548
 
            "Error in GnuTLS prime generation: %s\n",
 
519
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
549
520
            safer_gnutls_strerror(ret));
550
521
    goto globalfail;
551
522
  }
572
543
    }
573
544
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
574
545
  if(ret != GNUTLS_E_SUCCESS){
575
 
    fprintf(stderr, "Mandos plugin mandos-client: "
576
 
            "Error in GnuTLS session initialization: %s\n",
 
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
577
547
            safer_gnutls_strerror(ret));
578
548
  }
579
549
  
587
557
      }
588
558
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
589
559
    if(ret != GNUTLS_E_SUCCESS){
590
 
      fprintf(stderr, "Mandos plugin mandos-client: "
591
 
              "Syntax error at: %s\n", err);
592
 
      fprintf(stderr, "Mandos plugin mandos-client: "
593
 
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
 
560
      fprintf(stderr, "Syntax error at: %s\n", err);
 
561
      fprintf(stderr, "GnuTLS error: %s\n",
 
562
              safer_gnutls_strerror(ret));
594
563
      gnutls_deinit(*session);
595
564
      return -1;
596
565
    }
605
574
    }
606
575
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
607
576
  if(ret != GNUTLS_E_SUCCESS){
608
 
    fprintf(stderr, "Mandos plugin mandos-client: "
609
 
            "Error setting GnuTLS credentials: %s\n",
 
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
610
578
            safer_gnutls_strerror(ret));
611
579
    gnutls_deinit(*session);
612
580
    return -1;
658
626
    pf = PF_INET;
659
627
    break;
660
628
  default:
661
 
    fprintf(stderr, "Mandos plugin mandos-client: "
662
 
            "Bad address family: %d\n", af);
 
629
    fprintf(stderr, "Bad address family: %d\n", af);
663
630
    errno = EINVAL;
664
631
    return -1;
665
632
  }
670
637
  }
671
638
  
672
639
  if(debug){
673
 
    fprintf(stderr, "Mandos plugin mandos-client: "
674
 
            "Setting up a TCP connection to %s, port %" PRIu16
 
640
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
675
641
            "\n", ip, port);
676
642
  }
677
643
  
704
670
  }
705
671
  if(ret == 0){
706
672
    int e = errno;
707
 
    fprintf(stderr, "Mandos plugin mandos-client: "
708
 
            "Bad address: %s\n", ip);
 
673
    fprintf(stderr, "Bad address: %s\n", ip);
709
674
    errno = e;
710
675
    goto mandos_end;
711
676
  }
716
681
    
717
682
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
718
683
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
719
 
                                -Wunreachable-code*/
 
684
                              -Wunreachable-code*/
720
685
      if(if_index == AVAHI_IF_UNSPEC){
721
 
        fprintf(stderr, "Mandos plugin mandos-client: "
722
 
                "An IPv6 link-local address is incomplete"
 
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
723
687
                " without a network interface\n");
724
688
        errno = EINVAL;
725
689
        goto mandos_end;
744
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
745
709
        perror_plus("if_indextoname");
746
710
      } else {
747
 
        fprintf(stderr, "Mandos plugin mandos-client: "
748
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
749
712
                ip, interface, port);
750
713
      }
751
714
    } else {
752
 
      fprintf(stderr, "Mandos plugin mandos-client: "
753
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
715
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
716
              port);
754
717
    }
755
718
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
756
719
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
766
729
      perror_plus("inet_ntop");
767
730
    } else {
768
731
      if(strcmp(addrstr, ip) != 0){
769
 
        fprintf(stderr, "Mandos plugin mandos-client: "
770
 
                "Canonical address form: %s\n", addrstr);
 
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
771
733
      }
772
734
    }
773
735
  }
801
763
  while(true){
802
764
    size_t out_size = strlen(out);
803
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
804
 
                                        out_size - written));
 
766
                                   out_size - written));
805
767
    if(ret == -1){
806
768
      int e = errno;
807
769
      perror_plus("write");
827
789
  }
828
790
  
829
791
  if(debug){
830
 
    fprintf(stderr, "Mandos plugin mandos-client: "
831
 
            "Establishing TLS session with %s\n", ip);
 
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
832
793
  }
833
794
  
834
795
  if(quit_now){
835
796
    errno = EINTR;
836
797
    goto mandos_end;
837
798
  }
838
 
  
839
 
  /* Spurious warning from -Wint-to-pointer-cast */
 
799
 
 
800
  /* Spurious warnings from -Wint-to-pointer-cast */
840
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
841
802
  
842
803
  if(quit_now){
854
815
  
855
816
  if(ret != GNUTLS_E_SUCCESS){
856
817
    if(debug){
857
 
      fprintf(stderr, "Mandos plugin mandos-client: "
858
 
              "*** GnuTLS Handshake failed ***\n");
 
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
859
819
      gnutls_perror(ret);
860
820
    }
861
821
    errno = EPROTO;
865
825
  /* Read OpenPGP packet that contains the wanted password */
866
826
  
867
827
  if(debug){
868
 
    fprintf(stderr, "Mandos plugin mandos-client: "
869
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
828
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
829
            ip);
870
830
  }
871
831
  
872
832
  while(true){
877
837
    }
878
838
    
879
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
880
 
                                buffer_capacity);
 
840
                                   buffer_capacity);
881
841
    if(buffer_capacity == 0){
882
842
      int e = errno;
883
843
      perror_plus("incbuffer");
910
870
          }
911
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
912
872
        if(ret < 0){
913
 
          fprintf(stderr, "Mandos plugin mandos-client: "
914
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
915
874
          gnutls_perror(ret);
916
875
          errno = EPROTO;
917
876
          goto mandos_end;
918
877
        }
919
878
        break;
920
879
      default:
921
 
        fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                "Unknown error while reading data from"
 
880
        fprintf(stderr, "Unknown error while reading data from"
923
881
                " encrypted session with Mandos server\n");
924
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
925
883
        errno = EIO;
931
889
  }
932
890
  
933
891
  if(debug){
934
 
    fprintf(stderr, "Mandos plugin mandos-client: "
935
 
            "Closing TLS session\n");
 
892
    fprintf(stderr, "Closing TLS session\n");
936
893
  }
937
894
  
938
895
  if(quit_now){
950
907
  
951
908
  if(buffer_length > 0){
952
909
    ssize_t decrypted_buffer_size;
953
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
911
                                               buffer_length,
954
912
                                               &decrypted_buffer);
955
913
    if(decrypted_buffer_size >= 0){
956
914
      
967
925
        if(ret == 0 and ferror(stdout)){
968
926
          int e = errno;
969
927
          if(debug){
970
 
            fprintf(stderr, "Mandos plugin mandos-client: "
971
 
                    "Error writing encrypted data: %s\n",
 
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
972
929
                    strerror(errno));
973
930
          }
974
931
          errno = e;
1032
989
  switch(event){
1033
990
  default:
1034
991
  case AVAHI_RESOLVER_FAILURE:
1035
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1036
 
            "(Avahi Resolver) Failed to resolve service '%s'"
 
992
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
1037
993
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1038
994
            avahi_strerror(avahi_server_errno(mc.server)));
1039
995
    break;
1043
999
      char ip[AVAHI_ADDRESS_STR_MAX];
1044
1000
      avahi_address_snprint(ip, sizeof(ip), address);
1045
1001
      if(debug){
1046
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1047
 
                "Mandos server \"%s\" found on %s (%s, %"
 
1002
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1048
1003
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1049
1004
                ip, (intmax_t)interface, port);
1050
1005
      }
1084
1039
  default:
1085
1040
  case AVAHI_BROWSER_FAILURE:
1086
1041
    
1087
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1088
 
            "(Avahi browser) %s\n",
 
1042
    fprintf(stderr, "(Avahi browser) %s\n",
1089
1043
            avahi_strerror(avahi_server_errno(mc.server)));
1090
1044
    avahi_simple_poll_quit(mc.simple_poll);
1091
1045
    return;
1099
1053
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1100
1054
                                    name, type, domain, protocol, 0,
1101
1055
                                    resolve_callback, NULL) == NULL)
1102
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1103
 
              "Avahi: Failed to resolve service '%s': %s\n",
 
1056
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1104
1057
              name, avahi_strerror(avahi_server_errno(mc.server)));
1105
1058
    break;
1106
1059
    
1110
1063
  case AVAHI_BROWSER_ALL_FOR_NOW:
1111
1064
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1112
1065
    if(debug){
1113
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1114
 
              "No Mandos server found, still searching...\n");
 
1066
      fprintf(stderr, "No Mandos server found, still searching...\n");
1115
1067
    }
1116
1068
    break;
1117
1069
  }
1118
1070
}
1119
1071
 
1120
 
/* Signal handler that stops main loop after SIGTERM */
 
1072
/* Signal handler that stops main loop after sigterm has been called */
1121
1073
static void handle_sigterm(int sig){
1122
1074
  if(quit_now){
1123
1075
    return;
1132
1084
  errno = old_errno;
1133
1085
}
1134
1086
 
1135
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1136
 
  int ret;
1137
 
  
1138
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1139
 
  if(s < 0){
1140
 
    perror_plus("socket");
1141
 
    return false;
1142
 
  }
1143
 
  strcpy(ifr->ifr_name, ifname);
1144
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1145
 
  if(ret == -1){
 
1087
/* 
 
1088
 * This function determines if a directory entry in /sys/class/net
 
1089
 * corresponds to an acceptable network device.
 
1090
 * (This function is passed to scandir(3) as a filter function.)
 
1091
 */
 
1092
int good_interface(const struct dirent *if_entry){
 
1093
  ssize_t ssret;
 
1094
  char *flagname = NULL;
 
1095
  if(if_entry->d_name[0] == '.'){
 
1096
    return 0;
 
1097
  }
 
1098
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1099
                     if_entry->d_name);
 
1100
  if(ret < 0){
 
1101
    perror_plus("asprintf");
 
1102
    return 0;
 
1103
  }
 
1104
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1105
  if(flags_fd == -1){
 
1106
    perror_plus("open");
 
1107
    free(flagname);
 
1108
    return 0;
 
1109
  }
 
1110
  free(flagname);
 
1111
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1112
  /* read line from flags_fd */
 
1113
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1114
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1115
  flagstring[(size_t)to_read] = '\0';
 
1116
  if(flagstring == NULL){
 
1117
    perror_plus("malloc");
 
1118
    close(flags_fd);
 
1119
    return 0;
 
1120
  }
 
1121
  while(to_read > 0){
 
1122
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1123
                                             (size_t)to_read));
 
1124
    if(ssret == -1){
 
1125
      perror_plus("read");
 
1126
      free(flagstring);
 
1127
      close(flags_fd);
 
1128
      return 0;
 
1129
    }
 
1130
    to_read -= ssret;
 
1131
    if(ssret == 0){
 
1132
      break;
 
1133
    }
 
1134
  }
 
1135
  close(flags_fd);
 
1136
  intmax_t tmpmax;
 
1137
  char *tmp;
 
1138
  errno = 0;
 
1139
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1140
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1141
                                         and not (isspace(*tmp)))
 
1142
     or tmpmax != (ifreq_flags)tmpmax){
1146
1143
    if(debug){
1147
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1144
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1145
              flagstring, if_entry->d_name);
1148
1146
    }
1149
 
    return false;
 
1147
    free(flagstring);
 
1148
    return 0;
1150
1149
  }
1151
 
  return true;
1152
 
}
1153
 
 
1154
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1155
 
  
 
1150
  free(flagstring);
 
1151
  ifreq_flags flags = (ifreq_flags)tmpmax;
1156
1152
  /* Reject the loopback device */
1157
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1153
  if(flags & IFF_LOOPBACK){
1158
1154
    if(debug){
1159
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1160
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1155
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
              if_entry->d_name);
1161
1157
    }
1162
 
    return false;
 
1158
    return 0;
1163
1159
  }
1164
1160
  /* Accept point-to-point devices only if connect_to is specified */
1165
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1161
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1166
1162
    if(debug){
1167
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1168
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1163
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1164
              if_entry->d_name);
1169
1165
    }
1170
 
    return true;
 
1166
    return 1;
1171
1167
  }
1172
1168
  /* Otherwise, reject non-broadcast-capable devices */
1173
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1169
  if(not (flags & IFF_BROADCAST)){
1174
1170
    if(debug){
1175
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1176
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1171
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1172
              if_entry->d_name);
1177
1173
    }
1178
 
    return false;
 
1174
    return 0;
1179
1175
  }
1180
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
1181
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1177
  if(flags & IFF_NOARP){
1182
1178
    if(debug){
1183
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1184
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1179
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
              if_entry->d_name);
1185
1181
    }
1186
 
    return false;
 
1182
    return 0;
1187
1183
  }
1188
 
  
1189
1184
  /* Accept this device */
1190
1185
  if(debug){
1191
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1192
 
            "Interface \"%s\" is good\n", ifname);
1193
 
  }
1194
 
  return true;
1195
 
}
1196
 
 
1197
 
/* 
1198
 
 * This function determines if a directory entry in /sys/class/net
1199
 
 * corresponds to an acceptable network device.
1200
 
 * (This function is passed to scandir(3) as a filter function.)
1201
 
 */
1202
 
int good_interface(const struct dirent *if_entry){
1203
 
  if(if_entry->d_name[0] == '.'){
1204
 
    return 0;
1205
 
  }
1206
 
  
1207
 
  struct ifreq ifr;
1208
 
  if(not get_flags(if_entry->d_name, &ifr)){
1209
 
    if(debug){
1210
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1211
 
              "Failed to get flags for interface \"%s\"\n",
1212
 
              if_entry->d_name);
1213
 
    }
1214
 
    return 0;
1215
 
  }
1216
 
  
1217
 
  if(not good_flags(if_entry->d_name, &ifr)){
1218
 
    return 0;
1219
 
  }
1220
 
  return 1;
1221
 
}
1222
 
 
1223
 
/* 
1224
 
 * This function determines if a directory entry in /sys/class/net
1225
 
 * corresponds to an acceptable network device which is up.
1226
 
 * (This function is passed to scandir(3) as a filter function.)
1227
 
 */
1228
 
int up_interface(const struct dirent *if_entry){
1229
 
  if(if_entry->d_name[0] == '.'){
1230
 
    return 0;
1231
 
  }
1232
 
  
1233
 
  struct ifreq ifr;
1234
 
  if(not get_flags(if_entry->d_name, &ifr)){
1235
 
    if(debug){
1236
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1237
 
              "Failed to get flags for interface \"%s\"\n",
1238
 
              if_entry->d_name);
1239
 
    }
1240
 
    return 0;
1241
 
  }
1242
 
  
1243
 
  /* Reject down interfaces */
1244
 
  if(not (ifr.ifr_flags & IFF_UP)){
1245
 
    if(debug){
1246
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1247
 
              "Rejecting down interface \"%s\"\n",
1248
 
              if_entry->d_name);
1249
 
    }
1250
 
    return 0;
1251
 
  }
1252
 
  
1253
 
  /* Reject non-running interfaces */
1254
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1255
 
    if(debug){
1256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1257
 
              "Rejecting non-running interface \"%s\"\n",
1258
 
              if_entry->d_name);
1259
 
    }
1260
 
    return 0;
1261
 
  }
1262
 
  
1263
 
  if(not good_flags(if_entry->d_name, &ifr)){
1264
 
    return 0;
 
1186
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1187
            if_entry->d_name);
1265
1188
  }
1266
1189
  return 1;
1267
1190
}
1277
1200
  return 1;
1278
1201
}
1279
1202
 
1280
 
/* Is this directory entry a runnable program? */
1281
 
int runnable_hook(const struct dirent *direntry){
1282
 
  int ret;
1283
 
  size_t sret;
1284
 
  struct stat st;
1285
 
  
1286
 
  if((direntry->d_name)[0] == '\0'){
1287
 
    /* Empty name? */
1288
 
    return 0;
1289
 
  }
1290
 
  
1291
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1292
 
                "abcdefghijklmnopqrstuvwxyz"
1293
 
                "0123456789"
1294
 
                "_-");
1295
 
  if((direntry->d_name)[sret] != '\0'){
1296
 
    /* Contains non-allowed characters */
1297
 
    if(debug){
1298
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1299
 
              "Ignoring hook \"%s\" with bad name\n",
1300
 
              direntry->d_name);
1301
 
    }
1302
 
    return 0;
1303
 
  }
1304
 
  
1305
 
  char *fullname = NULL;
1306
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1307
 
  if(ret < 0){
1308
 
    perror_plus("asprintf");
1309
 
    return 0;
1310
 
  }
1311
 
  
1312
 
  ret = stat(fullname, &st);
1313
 
  if(ret == -1){
1314
 
    if(debug){
1315
 
      perror_plus("Could not stat hook");
1316
 
    }
1317
 
    return 0;
1318
 
  }
1319
 
  if(not (S_ISREG(st.st_mode))){
1320
 
    /* Not a regular file */
1321
 
    if(debug){
1322
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1323
 
              "Ignoring hook \"%s\" - not a file\n",
1324
 
              direntry->d_name);
1325
 
    }
1326
 
    return 0;
1327
 
  }
1328
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1329
 
    /* Not executable */
1330
 
    if(debug){
1331
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1332
 
              "Ignoring hook \"%s\" - not executable\n",
1333
 
              direntry->d_name);
1334
 
    }
1335
 
    return 0;
1336
 
  }
1337
 
  return 1;
1338
 
}
1339
 
 
1340
1203
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1341
1204
  int ret;
1342
1205
  struct timespec now;
1343
1206
  struct timespec waited_time;
1344
1207
  intmax_t block_time;
1345
 
  
 
1208
 
1346
1209
  while(true){
1347
1210
    if(mc.current_server == NULL){
1348
1211
      if (debug){
1349
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1350
 
                "Wait until first server is found. No timeout!\n");
 
1212
        fprintf(stderr, "Wait until first server is found. No timeout!\n");     
1351
1213
      }
1352
1214
      ret = avahi_simple_poll_iterate(s, -1);
1353
1215
    } else {
1354
1216
      if (debug){
1355
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1356
 
                "Check current_server if we should run it,"
1357
 
                " or wait\n");
 
1217
        fprintf(stderr, "Check current_server if we should run it, or wait\n"); 
1358
1218
      }
1359
1219
      /* the current time */
1360
1220
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1364
1224
      }
1365
1225
      /* Calculating in ms how long time between now and server
1366
1226
         who we visted longest time ago. Now - last seen.  */
1367
 
      waited_time.tv_sec = (now.tv_sec
1368
 
                            - mc.current_server->last_seen.tv_sec);
1369
 
      waited_time.tv_nsec = (now.tv_nsec
1370
 
                             - mc.current_server->last_seen.tv_nsec);
1371
 
      /* total time is 10s/10,000ms.
1372
 
         Converting to s from ms by dividing by 1,000,
1373
 
         and ns to ms by dividing by 1,000,000. */
1374
 
      block_time = ((retry_interval
1375
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1376
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1377
 
      
 
1227
      waited_time.tv_sec = now.tv_sec - mc.current_server->last_seen.tv_sec;
 
1228
      waited_time.tv_nsec = now.tv_nsec - mc.current_server->last_seen.tv_nsec;
 
1229
      /* total time is 10s/10000ms. Converting to s to ms by 1000/s, and ns to ms by divind by 1000000. */
 
1230
      block_time = (retry_interval - ((intmax_t)waited_time.tv_sec * 1000)) - ((intmax_t)waited_time.tv_nsec / 1000000);
 
1231
 
1378
1232
      if (debug){
1379
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1380
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1233
        fprintf(stderr, "Blocking for %ld ms\n", block_time);   
1381
1234
      }
1382
 
      
 
1235
 
1383
1236
      if(block_time <= 0){
1384
1237
        ret = start_mandos_communication(mc.current_server->ip,
1385
 
                                         mc.current_server->port,
1386
 
                                         mc.current_server->if_index,
1387
 
                                         mc.current_server->af);
 
1238
                                   mc.current_server->port,
 
1239
                                   mc.current_server->if_index,
 
1240
                                   mc.current_server->af);
1388
1241
        if(ret == 0){
1389
1242
          avahi_simple_poll_quit(mc.simple_poll);
1390
1243
          return 0;
1391
1244
        }
1392
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1393
 
                            &mc.current_server->last_seen);
 
1245
        ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
1394
1246
        if(ret == -1){
1395
1247
          perror_plus("clock_gettime");
1396
1248
          return -1;
1397
1249
        }
1398
1250
        mc.current_server = mc.current_server->next;
1399
 
        block_time = 0;         /* Call avahi to find new Mandos
1400
 
                                   servers, but don't block */
 
1251
        block_time = 0;         /* call avahi to find new mandos servers, but dont block */
1401
1252
      }
1402
1253
      
1403
1254
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1404
1255
    }
1405
1256
    if(ret != 0){
1406
 
      if (ret > 0 or errno != EINTR){
 
1257
      if (ret > 0 or errno != EINTR) {
1407
1258
        return (ret != 1) ? ret : 0;
1408
1259
      }
1409
1260
    }
1432
1283
  bool gnutls_initialized = false;
1433
1284
  bool gpgme_initialized = false;
1434
1285
  float delay = 2.5f;
1435
 
  double retry_interval = 10; /* 10s between trying a server and
1436
 
                                 retrying the same server again */
 
1286
  double retry_interval = 10; /* 10s between retrying a server and checking again*/
1437
1287
  
1438
1288
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1439
1289
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1497
1347
        .arg = "SECONDS",
1498
1348
        .doc = "Retry interval used when denied by the mandos server",
1499
1349
        .group = 2 },
1500
 
      { .name = "network-hook-dir", .key = 133,
1501
 
        .arg = "DIR",
1502
 
        .doc = "Directory where network hooks are located",
1503
 
        .group = 2 },
1504
1350
      /*
1505
1351
       * These reproduce what we would get without ARGP_NO_HELP
1506
1352
       */
1554
1400
        errno = 0;
1555
1401
        retry_interval = strtod(arg, &tmp);
1556
1402
        if(errno != 0 or tmp == arg or *tmp != '\0'
1557
 
           or (retry_interval * 1000) > INT_MAX
1558
 
           or retry_interval < 0){
 
1403
           or (retry_interval * 1000) > INT_MAX){
1559
1404
          argp_error(state, "Bad retry interval");
1560
1405
        }
1561
1406
        break;
1562
 
      case 133:                 /* --network-hook-dir */
1563
 
        hookdir = arg;
1564
 
        break;
1565
1407
        /*
1566
1408
         * These reproduce what we would get without ARGP_NO_HELP
1567
1409
         */
1573
1415
        argp_state_help(state, state->out_stream,
1574
1416
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1575
1417
      case 'V':                 /* --version */
1576
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1577
1418
        fprintf(state->out_stream, "%s\n", argp_program_version);
1578
1419
        exit(argp_err_exit_status);
1579
1420
        break;
1603
1444
      goto end;
1604
1445
    }
1605
1446
  }
1606
 
    
1607
 
  {
1608
 
    /* Work around Debian bug #633582:
1609
 
       <http://bugs.debian.org/633582> */
1610
 
    struct stat st;
1611
 
    
1612
 
    /* Re-raise priviliges */
1613
 
    errno = 0;
1614
 
    ret = seteuid(0);
1615
 
    if(ret == -1){
1616
 
      perror_plus("seteuid");
1617
 
    }
1618
 
    
1619
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1620
 
      int seckey_fd = open(seckey, O_RDONLY);
1621
 
      if(seckey_fd == -1){
1622
 
        perror_plus("open");
1623
 
      } else {
1624
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1625
 
        if(ret == -1){
1626
 
          perror_plus("fstat");
1627
 
        } else {
1628
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1629
 
            ret = fchown(seckey_fd, uid, gid);
1630
 
            if(ret == -1){
1631
 
              perror_plus("fchown");
1632
 
            }
1633
 
          }
1634
 
        }
1635
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1636
 
      }
1637
 
    }
1638
 
    
1639
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1640
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1641
 
      if(pubkey_fd == -1){
1642
 
        perror_plus("open");
1643
 
      } else {
1644
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1645
 
        if(ret == -1){
1646
 
          perror_plus("fstat");
1647
 
        } else {
1648
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1649
 
            ret = fchown(pubkey_fd, uid, gid);
1650
 
            if(ret == -1){
1651
 
              perror_plus("fchown");
1652
 
            }
1653
 
          }
1654
 
        }
1655
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1656
 
      }
1657
 
    }
1658
 
    
1659
 
    /* Lower privileges */
1660
 
    errno = 0;
1661
 
    ret = seteuid(uid);
1662
 
    if(ret == -1){
1663
 
      perror_plus("seteuid");
1664
 
    }
1665
 
  }
1666
 
  
1667
 
  /* Find network hooks and run them */
1668
 
  {
1669
 
    struct dirent **direntries;
1670
 
    struct dirent *direntry;
1671
 
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
1672
 
                           alphasort);
1673
 
    if(numhooks == -1){
1674
 
      perror_plus("scandir");
1675
 
    } else {
1676
 
      int devnull = open("/dev/null", O_RDONLY);
1677
 
      for(int i = 0; i < numhooks; i++){
1678
 
        direntry = direntries[0];
1679
 
        char *fullname = NULL;
1680
 
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1681
 
        if(ret < 0){
1682
 
          perror_plus("asprintf");
1683
 
          continue;
1684
 
        }
1685
 
        pid_t hook_pid = fork();
1686
 
        if(hook_pid == 0){
1687
 
          /* Child */
1688
 
          dup2(devnull, STDIN_FILENO);
1689
 
          close(devnull);
1690
 
          dup2(STDERR_FILENO, STDOUT_FILENO);
1691
 
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1692
 
          if(ret == -1){
1693
 
            perror_plus("setenv");
1694
 
            exit(1);
1695
 
          }
1696
 
          ret = setenv("DEVICE", interface, 1);
1697
 
          if(ret == -1){
1698
 
            perror_plus("setenv");
1699
 
            exit(1);
1700
 
          }
1701
 
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
1702
 
          if(ret == -1){
1703
 
            perror_plus("setenv");
1704
 
            exit(1);
1705
 
          }
1706
 
          ret = setenv("MODE", "start", 1);
1707
 
          if(ret == -1){
1708
 
            perror_plus("setenv");
1709
 
            exit(1);
1710
 
          }
1711
 
          char *delaystring;
1712
 
          ret = asprintf(&delaystring, "%f", delay);
1713
 
          if(ret == -1){
1714
 
            perror_plus("asprintf");
1715
 
            exit(1);
1716
 
          }
1717
 
          ret = setenv("DELAY", delaystring, 1);
1718
 
          if(ret == -1){
1719
 
            free(delaystring);
1720
 
            perror_plus("setenv");
1721
 
            exit(1);
1722
 
          }
1723
 
          free(delaystring);
1724
 
          ret = execl(fullname, direntry->d_name, "start", NULL);
1725
 
          perror_plus("execl");
1726
 
        } else {
1727
 
          int status;
1728
 
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1729
 
            perror_plus("waitpid");
1730
 
            free(fullname);
1731
 
            continue;
1732
 
          }
1733
 
          if(WIFEXITED(status)){
1734
 
            if(WEXITSTATUS(status) != 0){
1735
 
              fprintf(stderr, "Mandos plugin mandos-client: "
1736
 
                      "Warning: network hook \"%s\" exited"
1737
 
                      " with status %d\n", direntry->d_name,
1738
 
                      WEXITSTATUS(status));
1739
 
              free(fullname);
1740
 
              continue;
1741
 
            }
1742
 
          } else if(WIFSIGNALED(status)){
1743
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1744
 
                    "Warning: network hook \"%s\" died by"
1745
 
                    " signal %d\n", direntry->d_name,
1746
 
                    WTERMSIG(status));
1747
 
            free(fullname);
1748
 
            continue;
1749
 
          } else {
1750
 
            fprintf(stderr, "Mandos plugin mandos-client: "
1751
 
                    "Warning: network hook \"%s\" crashed\n",
1752
 
                    direntry->d_name);
1753
 
            free(fullname);
1754
 
            continue;
1755
 
          }
1756
 
        }
1757
 
        free(fullname);
1758
 
        if(quit_now){
1759
 
          goto end;
1760
 
        }
1761
 
      }
1762
 
      close(devnull);
1763
 
    }
1764
 
  }
1765
1447
  
1766
1448
  if(not debug){
1767
1449
    avahi_set_log_function(empty_log);
1768
1450
  }
1769
 
  
 
1451
 
1770
1452
  if(interface[0] == '\0'){
1771
1453
    struct dirent **direntries;
1772
 
    /* First look for interfaces that are up */
1773
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1454
    ret = scandir(sys_class_net, &direntries, good_interface,
1774
1455
                  alphasort);
1775
 
    if(ret == 0){
1776
 
      /* No up interfaces, look for any good interfaces */
1777
 
      free(direntries);
1778
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1779
 
                    alphasort);
1780
 
    }
1781
1456
    if(ret >= 1){
1782
 
      /* Pick the first interface returned */
 
1457
      /* Pick the first good interface */
1783
1458
      interface = strdup(direntries[0]->d_name);
1784
1459
      if(debug){
1785
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1786
 
                "Using interface \"%s\"\n", interface);
 
1460
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1787
1461
      }
1788
1462
      if(interface == NULL){
1789
1463
        perror_plus("malloc");
1794
1468
      free(direntries);
1795
1469
    } else {
1796
1470
      free(direntries);
1797
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1798
 
              "Could not find a network interface\n");
 
1471
      fprintf(stderr, "Could not find a network interface\n");
1799
1472
      exitcode = EXIT_FAILURE;
1800
1473
      goto end;
1801
1474
    }
1807
1480
  srand((unsigned int) time(NULL));
1808
1481
  mc.simple_poll = avahi_simple_poll_new();
1809
1482
  if(mc.simple_poll == NULL){
1810
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1811
 
            "Avahi: Failed to create simple poll object.\n");
 
1483
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1812
1484
    exitcode = EX_UNAVAILABLE;
1813
1485
    goto end;
1814
1486
  }
1880
1552
  if(strcmp(interface, "none") != 0){
1881
1553
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1882
1554
    if(if_index == 0){
1883
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1884
 
              "No such interface: \"%s\"\n", interface);
 
1555
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1885
1556
      exitcode = EX_UNAVAILABLE;
1886
1557
      goto end;
1887
1558
    }
1974
1645
        goto end;
1975
1646
      }
1976
1647
    }
1977
 
    /* Sleep checking until interface is running.
1978
 
       Check every 0.25s, up to total time of delay */
 
1648
    /* sleep checking until interface is running. Check every 0.25s, up to total time of delay */
1979
1649
    for(int i=0; i < delay * 4; i++){
1980
1650
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1981
1651
      if(ret == -1){
2028
1698
  
2029
1699
  ret = init_gnutls_global(pubkey, seckey);
2030
1700
  if(ret == -1){
2031
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2032
 
            "init_gnutls_global failed\n");
 
1701
    fprintf(stderr, "init_gnutls_global failed\n");
2033
1702
    exitcode = EX_UNAVAILABLE;
2034
1703
    goto end;
2035
1704
  } else {
2051
1720
  }
2052
1721
  
2053
1722
  if(not init_gpgme(pubkey, seckey, tempdir)){
2054
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2055
 
            "init_gpgme failed\n");
 
1723
    fprintf(stderr, "init_gpgme failed\n");
2056
1724
    exitcode = EX_UNAVAILABLE;
2057
1725
    goto end;
2058
1726
  } else {
2068
1736
    /* (Mainly meant for debugging) */
2069
1737
    char *address = strrchr(connect_to, ':');
2070
1738
    if(address == NULL){
2071
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2072
 
              "No colon in address\n");
 
1739
      fprintf(stderr, "No colon in address\n");
2073
1740
      exitcode = EX_USAGE;
2074
1741
      goto end;
2075
1742
    }
2083
1750
    tmpmax = strtoimax(address+1, &tmp, 10);
2084
1751
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2085
1752
       or tmpmax != (uint16_t)tmpmax){
2086
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2087
 
              "Bad port number\n");
 
1753
      fprintf(stderr, "Bad port number\n");
2088
1754
      exitcode = EX_USAGE;
2089
1755
      goto end;
2090
1756
    }
2095
1761
    
2096
1762
    port = (uint16_t)tmpmax;
2097
1763
    *address = '\0';
 
1764
    address = connect_to;
2098
1765
    /* Colon in address indicates IPv6 */
2099
1766
    int af;
2100
 
    if(strchr(connect_to, ':') != NULL){
 
1767
    if(strchr(address, ':') != NULL){
2101
1768
      af = AF_INET6;
2102
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2103
 
      if(connect_to[0] == '[' and address[-1] == ']')
2104
 
        {
2105
 
          connect_to++;
2106
 
          address[-1] = '\0';
2107
 
        }
2108
1769
    } else {
2109
1770
      af = AF_INET;
2110
1771
    }
2111
 
    address = connect_to;
2112
1772
    
2113
1773
    if(quit_now){
2114
1774
      goto end;
2115
1775
    }
2116
 
    
 
1776
 
2117
1777
    while(not quit_now){
2118
1778
      ret = start_mandos_communication(address, port, if_index, af);
2119
1779
      if(quit_now or ret == 0){
2120
1780
        break;
2121
1781
      }
2122
 
      if(debug){
2123
 
        fprintf(stderr, "Mandos plugin mandos-client: "
2124
 
                "Retrying in %d seconds\n", (int)retry_interval);
2125
 
      }
2126
 
      sleep((int)retry_interval);
2127
 
    }
2128
 
    
 
1782
      sleep((int)retry_interval or 1);
 
1783
    };
 
1784
 
2129
1785
    if (not quit_now){
2130
1786
      exitcode = EXIT_SUCCESS;
2131
1787
    }
2132
 
    
 
1788
 
2133
1789
    goto end;
2134
1790
  }
2135
1791
  
2157
1813
  
2158
1814
  /* Check if creating the Avahi server object succeeded */
2159
1815
  if(mc.server == NULL){
2160
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2161
 
            "Failed to create Avahi server: %s\n",
 
1816
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2162
1817
            avahi_strerror(error));
2163
1818
    exitcode = EX_UNAVAILABLE;
2164
1819
    goto end;
2173
1828
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2174
1829
                                   NULL, 0, browse_callback, NULL);
2175
1830
  if(sb == NULL){
2176
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2177
 
            "Failed to create service browser: %s\n",
 
1831
    fprintf(stderr, "Failed to create service browser: %s\n",
2178
1832
            avahi_strerror(avahi_server_errno(mc.server)));
2179
1833
    exitcode = EX_UNAVAILABLE;
2180
1834
    goto end;
2187
1841
  /* Run the main loop */
2188
1842
  
2189
1843
  if(debug){
2190
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2191
 
            "Starting Avahi loop search\n");
 
1844
    fprintf(stderr, "Starting Avahi loop search\n");
2192
1845
  }
2193
1846
 
2194
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2195
 
                                (int)(retry_interval * 1000));
 
1847
  ret = avahi_loop_with_timeout(mc.simple_poll, (int)(retry_interval * 1000));
2196
1848
  if(debug){
2197
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2198
 
            "avahi_loop_with_timeout exited %s\n",
 
1849
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2199
1850
            (ret == 0) ? "successfully" : "with error");
2200
1851
  }
2201
1852
  
2202
1853
 end:
2203
1854
  
2204
1855
  if(debug){
2205
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2206
 
            "%s exiting\n", argv[0]);
 
1856
    fprintf(stderr, "%s exiting\n", argv[0]);
2207
1857
  }
2208
1858
  
2209
1859
  /* Cleanup things */
2226
1876
    gpgme_release(mc.ctx);
2227
1877
  }
2228
1878
 
2229
 
  /* Cleans up the circular linked list of Mandos servers the client
2230
 
     has seen */
 
1879
  /* cleans up the circular linked list of mandos servers the client has seen */
2231
1880
  if(mc.current_server != NULL){
2232
1881
    mc.current_server->prev->next = NULL;
2233
1882
    while(mc.current_server != NULL){
2237
1886
    }
2238
1887
  }
2239
1888
  
2240
 
  /* XXX run network hooks "stop" here  */
2241
 
  
2242
1889
  /* Take down the network interface */
2243
1890
  if(take_down_interface){
2244
1891
    /* Re-raise priviliges */
2251
1898
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2252
1899
      if(ret == -1){
2253
1900
        perror_plus("ioctl SIOCGIFFLAGS");
2254
 
      } else if(network.ifr_flags & IFF_UP){
 
1901
      } else if(network.ifr_flags & IFF_UP) {
2255
1902
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2256
1903
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2257
1904
        if(ret == -1){
2275
1922
  if(tempdir_created){
2276
1923
    struct dirent **direntries = NULL;
2277
1924
    struct dirent *direntry = NULL;
2278
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2279
 
                             alphasort);
2280
 
    if (numentries > 0){
2281
 
      for(int i = 0; i < numentries; i++){
 
1925
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1926
    if (ret > 0){
 
1927
      for(int i = 0; i < ret; i++){
2282
1928
        direntry = direntries[i];
2283
1929
        char *fullname = NULL;
2284
1930
        ret = asprintf(&fullname, "%s/%s", tempdir,
2289
1935
        }
2290
1936
        ret = remove(fullname);
2291
1937
        if(ret == -1){
2292
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2293
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
1938
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1939
                  strerror(errno));
2294
1940
        }
2295
1941
        free(fullname);
2296
1942
      }
2297
1943
    }
2298
1944
 
2299
 
    /* need to clean even if 0 because man page doesn't specify */
 
1945
    /* need to be cleaned even if ret == 0 because man page dont specify */
2300
1946
    free(direntries);
2301
 
    if (numentries == -1){
 
1947
    if (ret == -1){
2302
1948
      perror_plus("scandir");
2303
1949
    }
2304
1950
    ret = rmdir(tempdir);