/mandos/trunk

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

« back to all changes in this revision

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

merge

Show diffs side-by-side

added added

removed removed

Lines of Context:
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@fukt.bsnet.se>.
 
29
 * Contact the authors at <mandos@recompile.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open() */
 
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
88
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
89
                                   WEXITSTATUS(), WTERMSIG() */
88
90
 
89
91
#ifdef __linux__
90
92
#include <sys/klog.h>           /* klogctl() */
108
110
                                   init_gnutls_session(),
109
111
                                   GNUTLS_* */
110
112
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
113
                         /* gnutls_certificate_set_openpgp_key_file(),
 
114
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
115
 
114
116
/* GPGME */
115
117
#include <gpgme.h>              /* All GPGME types, constants and
123
125
#define PATHDIR "/conf/conf.d/mandos"
124
126
#define SECKEY "seckey.txt"
125
127
#define PUBKEY "pubkey.txt"
 
128
#define HOOKDIR "/lib/mandos/network-hooks.d"
126
129
 
127
130
bool debug = false;
128
131
static const char mandos_protocol_version[] = "1";
129
132
const char *argp_program_version = "mandos-client " VERSION;
130
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
133
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
134
static const char sys_class_net[] = "/sys/class/net";
132
135
char *connect_to = NULL;
 
136
const char *hookdir = HOOKDIR;
133
137
 
134
138
/* Doubly linked list that need to be circularly linked when used */
135
139
typedef struct server{
170
174
  perror(print_text);
171
175
}
172
176
 
 
177
int fprintf_plus(FILE *stream, const char *format, ...){
 
178
  va_list ap;
 
179
  va_start (ap, format);
 
180
  
 
181
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", program_invocation_short_name));
 
182
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
183
}
 
184
 
173
185
/*
174
186
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
187
 * bytes. "buffer_capacity" is how much is currently allocated,
176
188
 * "buffer_length" is how much is already used.
177
189
 */
178
190
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
191
                 size_t buffer_capacity){
180
192
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
193
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
194
    if(buffer == NULL){
187
199
  return buffer_capacity;
188
200
}
189
201
 
190
 
int add_server(const char *ip, uint16_t port,
191
 
                 AvahiIfIndex if_index,
192
 
                 int af){
 
202
/* Add server to set of servers to retry periodically */
 
203
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
204
               int af){
193
205
  int ret;
194
206
  server *new_server = malloc(sizeof(server));
195
207
  if(new_server == NULL){
197
209
    return -1;
198
210
  }
199
211
  *new_server = (server){ .ip = strdup(ip),
200
 
                         .port = port,
201
 
                         .if_index = if_index,
202
 
                         .af = af };
 
212
                          .port = port,
 
213
                          .if_index = if_index,
 
214
                          .af = af };
203
215
  if(new_server->ip == NULL){
204
216
    perror_plus("strdup");
205
217
    return -1;
206
218
  }
207
 
  /* unique case of first server */
 
219
  /* Special case of first server */
208
220
  if (mc.current_server == NULL){
209
221
    new_server->next = new_server;
210
222
    new_server->prev = new_server;
211
223
    mc.current_server = new_server;
212
 
  /* Placing the new server last in the list */
 
224
  /* Place the new server last in the list */
213
225
  } else {
214
226
    new_server->next = mc.current_server;
215
227
    new_server->prev = mc.current_server->prev;
227
239
/* 
228
240
 * Initialize GPGME.
229
241
 */
230
 
static bool init_gpgme(const char *seckey,
231
 
                       const char *pubkey, const char *tempdir){
 
242
static bool init_gpgme(const char *seckey, const char *pubkey,
 
243
                       const char *tempdir){
232
244
  gpgme_error_t rc;
233
245
  gpgme_engine_info_t engine_info;
234
246
  
249
261
    
250
262
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
251
263
    if(rc != GPG_ERR_NO_ERROR){
252
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
265
              "bad gpgme_data_new_from_fd: %s: %s\n",
253
266
              gpgme_strsource(rc), gpgme_strerror(rc));
254
267
      return false;
255
268
    }
256
269
    
257
270
    rc = gpgme_op_import(mc.ctx, pgp_data);
258
271
    if(rc != GPG_ERR_NO_ERROR){
259
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
272
      fprintf(stderr, "Mandos plugin mandos-client: "
 
273
              "bad gpgme_op_import: %s: %s\n",
260
274
              gpgme_strsource(rc), gpgme_strerror(rc));
261
275
      return false;
262
276
    }
270
284
  }
271
285
  
272
286
  if(debug){
273
 
    fprintf(stderr, "Initializing GPGME\n");
 
287
    fprintf(stderr, "Mandos plugin mandos-client: "
 
288
            "Initializing GPGME\n");
274
289
  }
275
290
  
276
291
  /* Init GPGME */
277
292
  gpgme_check_version(NULL);
278
293
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
279
294
  if(rc != GPG_ERR_NO_ERROR){
280
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
295
    fprintf(stderr, "Mandos plugin mandos-client: "
 
296
            "bad gpgme_engine_check_version: %s: %s\n",
281
297
            gpgme_strsource(rc), gpgme_strerror(rc));
282
298
    return false;
283
299
  }
284
300
  
285
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
301
  /* Set GPGME home directory for the OpenPGP engine only */
286
302
  rc = gpgme_get_engine_info(&engine_info);
287
303
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
304
    fprintf(stderr, "Mandos plugin mandos-client: "
 
305
            "bad gpgme_get_engine_info: %s: %s\n",
289
306
            gpgme_strsource(rc), gpgme_strerror(rc));
290
307
    return false;
291
308
  }
298
315
    engine_info = engine_info->next;
299
316
  }
300
317
  if(engine_info == NULL){
301
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
318
    fprintf(stderr, "Mandos plugin mandos-client: "
 
319
            "Could not set GPGME home dir to %s\n", tempdir);
302
320
    return false;
303
321
  }
304
322
  
305
323
  /* Create new GPGME "context" */
306
324
  rc = gpgme_new(&(mc.ctx));
307
325
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
309
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
326
    fprintf(stderr, "Mandos plugin mandos-client: "
 
327
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
328
            gpgme_strerror(rc));
310
329
    return false;
311
330
  }
312
331
  
331
350
  ssize_t plaintext_length = 0;
332
351
  
333
352
  if(debug){
334
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
353
    fprintf(stderr, "Mandos plugin mandos-client: "
 
354
            "Trying to decrypt OpenPGP data\n");
335
355
  }
336
356
  
337
357
  /* Create new GPGME data buffer from memory cryptotext */
338
358
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
339
359
                               0);
340
360
  if(rc != GPG_ERR_NO_ERROR){
341
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
361
    fprintf(stderr, "Mandos plugin mandos-client: "
 
362
            "bad gpgme_data_new_from_mem: %s: %s\n",
342
363
            gpgme_strsource(rc), gpgme_strerror(rc));
343
364
    return -1;
344
365
  }
346
367
  /* Create new empty GPGME data buffer for the plaintext */
347
368
  rc = gpgme_data_new(&dh_plain);
348
369
  if(rc != GPG_ERR_NO_ERROR){
349
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
370
    fprintf(stderr, "Mandos plugin mandos-client: "
 
371
            "bad gpgme_data_new: %s: %s\n",
350
372
            gpgme_strsource(rc), gpgme_strerror(rc));
351
373
    gpgme_data_release(dh_crypto);
352
374
    return -1;
356
378
     data buffer */
357
379
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
358
380
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
381
    fprintf(stderr, "Mandos plugin mandos-client: "
 
382
            "bad gpgme_op_decrypt: %s: %s\n",
360
383
            gpgme_strsource(rc), gpgme_strerror(rc));
361
384
    plaintext_length = -1;
362
385
    if(debug){
363
386
      gpgme_decrypt_result_t result;
364
387
      result = gpgme_op_decrypt_result(mc.ctx);
365
388
      if(result == NULL){
366
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
389
        fprintf(stderr, "Mandos plugin mandos-client: "
 
390
                "gpgme_op_decrypt_result failed\n");
367
391
      } else {
368
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
392
        fprintf(stderr, "Mandos plugin mandos-client: "
 
393
                "Unsupported algorithm: %s\n",
369
394
                result->unsupported_algorithm);
370
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
395
        fprintf(stderr, "Mandos plugin mandos-client: "
 
396
                "Wrong key usage: %u\n",
371
397
                result->wrong_key_usage);
372
398
        if(result->file_name != NULL){
373
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
399
          fprintf(stderr, "Mandos plugin mandos-client: "
 
400
                  "File name: %s\n", result->file_name);
374
401
        }
375
402
        gpgme_recipient_t recipient;
376
403
        recipient = result->recipients;
377
404
        while(recipient != NULL){
378
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
405
          fprintf(stderr, "Mandos plugin mandos-client: "
 
406
                  "Public key algorithm: %s\n",
379
407
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
380
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
381
 
          fprintf(stderr, "Secret key available: %s\n",
 
408
          fprintf(stderr, "Mandos plugin mandos-client: "
 
409
                  "Key ID: %s\n", recipient->keyid);
 
410
          fprintf(stderr, "Mandos plugin mandos-client: "
 
411
                  "Secret key available: %s\n",
382
412
                  recipient->status == GPG_ERR_NO_SECKEY
383
413
                  ? "No" : "Yes");
384
414
          recipient = recipient->next;
389
419
  }
390
420
  
391
421
  if(debug){
392
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
422
    fprintf(stderr, "Mandos plugin mandos-client: "
 
423
            "Decryption of OpenPGP data succeeded\n");
393
424
  }
394
425
  
395
426
  /* Seek back to the beginning of the GPGME plaintext data buffer */
402
433
  *plaintext = NULL;
403
434
  while(true){
404
435
    plaintext_capacity = incbuffer(plaintext,
405
 
                                      (size_t)plaintext_length,
406
 
                                      plaintext_capacity);
 
436
                                   (size_t)plaintext_length,
 
437
                                   plaintext_capacity);
407
438
    if(plaintext_capacity == 0){
408
 
        perror_plus("incbuffer");
409
 
        plaintext_length = -1;
410
 
        goto decrypt_end;
 
439
      perror_plus("incbuffer");
 
440
      plaintext_length = -1;
 
441
      goto decrypt_end;
411
442
    }
412
443
    
413
444
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
426
457
  }
427
458
  
428
459
  if(debug){
429
 
    fprintf(stderr, "Decrypted password is: ");
 
460
    fprintf(stderr, "Mandos plugin mandos-client: "
 
461
            "Decrypted password is: ");
430
462
    for(ssize_t i = 0; i < plaintext_length; i++){
431
463
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
432
464
    }
454
486
/* GnuTLS log function callback */
455
487
static void debuggnutls(__attribute__((unused)) int level,
456
488
                        const char* string){
457
 
  fprintf(stderr, "GnuTLS: %s", string);
 
489
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
458
490
}
459
491
 
460
492
static int init_gnutls_global(const char *pubkeyfilename,
462
494
  int ret;
463
495
  
464
496
  if(debug){
465
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
497
    fprintf(stderr, "Mandos plugin mandos-client: "
 
498
            "Initializing GnuTLS\n");
466
499
  }
467
500
  
468
501
  ret = gnutls_global_init();
469
502
  if(ret != GNUTLS_E_SUCCESS){
470
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
471
 
            safer_gnutls_strerror(ret));
 
503
    fprintf(stderr, "Mandos plugin mandos-client: "
 
504
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
472
505
    return -1;
473
506
  }
474
507
  
483
516
  /* OpenPGP credentials */
484
517
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
485
518
  if(ret != GNUTLS_E_SUCCESS){
486
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
487
 
            safer_gnutls_strerror(ret));
 
519
    fprintf(stderr, "Mandos plugin mandos-client: "
 
520
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
488
521
    gnutls_global_deinit();
489
522
    return -1;
490
523
  }
491
524
  
492
525
  if(debug){
493
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
526
    fprintf(stderr, "Mandos plugin mandos-client: "
 
527
            "Attempting to use OpenPGP public key %s and"
494
528
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
495
529
            seckeyfilename);
496
530
  }
500
534
     GNUTLS_OPENPGP_FMT_BASE64);
501
535
  if(ret != GNUTLS_E_SUCCESS){
502
536
    fprintf(stderr,
 
537
            "Mandos plugin mandos-client: "
503
538
            "Error[%d] while reading the OpenPGP key pair ('%s',"
504
539
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
505
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
506
 
            safer_gnutls_strerror(ret));
 
540
    fprintf(stderr, "Mandos plugin mandos-client: "
 
541
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
507
542
    goto globalfail;
508
543
  }
509
544
  
510
545
  /* GnuTLS server initialization */
511
546
  ret = gnutls_dh_params_init(&mc.dh_params);
512
547
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
548
    fprintf(stderr, "Mandos plugin mandos-client: "
 
549
            "Error in GnuTLS DH parameter initialization:"
514
550
            " %s\n", safer_gnutls_strerror(ret));
515
551
    goto globalfail;
516
552
  }
517
553
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
518
554
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
555
    fprintf(stderr, "Mandos plugin mandos-client: "
 
556
            "Error in GnuTLS prime generation: %s\n",
520
557
            safer_gnutls_strerror(ret));
521
558
    goto globalfail;
522
559
  }
543
580
    }
544
581
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
545
582
  if(ret != GNUTLS_E_SUCCESS){
546
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
583
    fprintf(stderr, "Mandos plugin mandos-client: "
 
584
            "Error in GnuTLS session initialization: %s\n",
547
585
            safer_gnutls_strerror(ret));
548
586
  }
549
587
  
557
595
      }
558
596
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
559
597
    if(ret != GNUTLS_E_SUCCESS){
560
 
      fprintf(stderr, "Syntax error at: %s\n", err);
561
 
      fprintf(stderr, "GnuTLS error: %s\n",
562
 
              safer_gnutls_strerror(ret));
 
598
      fprintf(stderr, "Mandos plugin mandos-client: "
 
599
              "Syntax error at: %s\n", err);
 
600
      fprintf(stderr, "Mandos plugin mandos-client: "
 
601
              "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
563
602
      gnutls_deinit(*session);
564
603
      return -1;
565
604
    }
574
613
    }
575
614
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
576
615
  if(ret != GNUTLS_E_SUCCESS){
577
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
616
    fprintf(stderr, "Mandos plugin mandos-client: "
 
617
            "Error setting GnuTLS credentials: %s\n",
578
618
            safer_gnutls_strerror(ret));
579
619
    gnutls_deinit(*session);
580
620
    return -1;
626
666
    pf = PF_INET;
627
667
    break;
628
668
  default:
629
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
669
    fprintf(stderr, "Mandos plugin mandos-client: "
 
670
            "Bad address family: %d\n", af);
630
671
    errno = EINVAL;
631
672
    return -1;
632
673
  }
637
678
  }
638
679
  
639
680
  if(debug){
640
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
681
    fprintf(stderr, "Mandos plugin mandos-client: "
 
682
            "Setting up a TCP connection to %s, port %" PRIu16
641
683
            "\n", ip, port);
642
684
  }
643
685
  
670
712
  }
671
713
  if(ret == 0){
672
714
    int e = errno;
673
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
715
    fprintf(stderr, "Mandos plugin mandos-client: "
 
716
            "Bad address: %s\n", ip);
674
717
    errno = e;
675
718
    goto mandos_end;
676
719
  }
681
724
    
682
725
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
683
726
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
684
 
                              -Wunreachable-code*/
 
727
                                -Wunreachable-code*/
685
728
      if(if_index == AVAHI_IF_UNSPEC){
686
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
729
        fprintf(stderr, "Mandos plugin mandos-client: "
 
730
                "An IPv6 link-local address is incomplete"
687
731
                " without a network interface\n");
688
732
        errno = EINVAL;
689
733
        goto mandos_end;
708
752
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
753
        perror_plus("if_indextoname");
710
754
      } else {
711
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
755
        fprintf(stderr, "Mandos plugin mandos-client: "
 
756
                "Connection to: %s%%%s, port %" PRIu16 "\n",
712
757
                ip, interface, port);
713
758
      }
714
759
    } else {
715
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
716
 
              port);
 
760
      fprintf(stderr, "Mandos plugin mandos-client: "
 
761
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
717
762
    }
718
763
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
719
764
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
729
774
      perror_plus("inet_ntop");
730
775
    } else {
731
776
      if(strcmp(addrstr, ip) != 0){
732
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
777
        fprintf(stderr, "Mandos plugin mandos-client: "
 
778
                "Canonical address form: %s\n", addrstr);
733
779
      }
734
780
    }
735
781
  }
763
809
  while(true){
764
810
    size_t out_size = strlen(out);
765
811
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
 
                                   out_size - written));
 
812
                                        out_size - written));
767
813
    if(ret == -1){
768
814
      int e = errno;
769
815
      perror_plus("write");
789
835
  }
790
836
  
791
837
  if(debug){
792
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
838
    fprintf(stderr, "Mandos plugin mandos-client: "
 
839
            "Establishing TLS session with %s\n", ip);
793
840
  }
794
841
  
795
842
  if(quit_now){
815
862
  
816
863
  if(ret != GNUTLS_E_SUCCESS){
817
864
    if(debug){
818
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
865
      fprintf(stderr, "Mandos plugin mandos-client: "
 
866
              "*** GnuTLS Handshake failed ***\n");
819
867
      gnutls_perror(ret);
820
868
    }
821
869
    errno = EPROTO;
825
873
  /* Read OpenPGP packet that contains the wanted password */
826
874
  
827
875
  if(debug){
828
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
829
 
            ip);
 
876
    fprintf(stderr, "Mandos plugin mandos-client: "
 
877
            "Retrieving OpenPGP encrypted password from %s\n", ip);
830
878
  }
831
879
  
832
880
  while(true){
837
885
    }
838
886
    
839
887
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
 
                                   buffer_capacity);
 
888
                                buffer_capacity);
841
889
    if(buffer_capacity == 0){
842
890
      int e = errno;
843
891
      perror_plus("incbuffer");
870
918
          }
871
919
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
920
        if(ret < 0){
873
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
921
          fprintf(stderr, "Mandos plugin mandos-client: "
 
922
                  "*** GnuTLS Re-handshake failed ***\n");
874
923
          gnutls_perror(ret);
875
924
          errno = EPROTO;
876
925
          goto mandos_end;
877
926
        }
878
927
        break;
879
928
      default:
880
 
        fprintf(stderr, "Unknown error while reading data from"
 
929
        fprintf(stderr, "Mandos plugin mandos-client: "
 
930
                "Unknown error while reading data from"
881
931
                " encrypted session with Mandos server\n");
882
932
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
933
        errno = EIO;
889
939
  }
890
940
  
891
941
  if(debug){
892
 
    fprintf(stderr, "Closing TLS session\n");
 
942
    fprintf(stderr, "Mandos plugin mandos-client: "
 
943
            "Closing TLS session\n");
893
944
  }
894
945
  
895
946
  if(quit_now){
907
958
  
908
959
  if(buffer_length > 0){
909
960
    ssize_t decrypted_buffer_size;
910
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
911
 
                                               buffer_length,
 
961
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
912
962
                                               &decrypted_buffer);
913
963
    if(decrypted_buffer_size >= 0){
914
964
      
925
975
        if(ret == 0 and ferror(stdout)){
926
976
          int e = errno;
927
977
          if(debug){
928
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
978
            fprintf(stderr, "Mandos plugin mandos-client: "
 
979
                    "Error writing encrypted data: %s\n",
929
980
                    strerror(errno));
930
981
          }
931
982
          errno = e;
989
1040
  switch(event){
990
1041
  default:
991
1042
  case AVAHI_RESOLVER_FAILURE:
992
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
1043
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1044
            "(Avahi Resolver) Failed to resolve service '%s'"
993
1045
            " of type '%s' in domain '%s': %s\n", name, type, domain,
994
1046
            avahi_strerror(avahi_server_errno(mc.server)));
995
1047
    break;
999
1051
      char ip[AVAHI_ADDRESS_STR_MAX];
1000
1052
      avahi_address_snprint(ip, sizeof(ip), address);
1001
1053
      if(debug){
1002
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1054
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1055
                "Mandos server \"%s\" found on %s (%s, %"
1003
1056
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1004
1057
                ip, (intmax_t)interface, port);
1005
1058
      }
1039
1092
  default:
1040
1093
  case AVAHI_BROWSER_FAILURE:
1041
1094
    
1042
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1095
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1096
            "(Avahi browser) %s\n",
1043
1097
            avahi_strerror(avahi_server_errno(mc.server)));
1044
1098
    avahi_simple_poll_quit(mc.simple_poll);
1045
1099
    return;
1053
1107
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1054
1108
                                    name, type, domain, protocol, 0,
1055
1109
                                    resolve_callback, NULL) == NULL)
1056
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1110
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1111
              "Avahi: Failed to resolve service '%s': %s\n",
1057
1112
              name, avahi_strerror(avahi_server_errno(mc.server)));
1058
1113
    break;
1059
1114
    
1063
1118
  case AVAHI_BROWSER_ALL_FOR_NOW:
1064
1119
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1065
1120
    if(debug){
1066
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1121
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1122
              "No Mandos server found, still searching...\n");
1067
1123
    }
1068
1124
    break;
1069
1125
  }
1084
1140
  errno = old_errno;
1085
1141
}
1086
1142
 
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 = 2+(sizeof(ifreq_flags)*2)+1; /* "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){
 
1143
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1144
  int ret;
 
1145
  
 
1146
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1147
  if(s < 0){
 
1148
    perror_plus("socket");
 
1149
    return false;
 
1150
  }
 
1151
  strcpy(ifr->ifr_name, ifname);
 
1152
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1153
  if(ret == -1){
1143
1154
    if(debug){
1144
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1145
 
              flagstring, if_entry->d_name);
 
1155
      perror_plus("ioctl SIOCGIFFLAGS");
1146
1156
    }
1147
 
    free(flagstring);
1148
 
    return 0;
 
1157
    return false;
1149
1158
  }
1150
 
  free(flagstring);
1151
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1159
  return true;
 
1160
}
 
1161
 
 
1162
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1163
  
1152
1164
  /* Reject the loopback device */
1153
 
  if(flags & IFF_LOOPBACK){
 
1165
  if(ifr->ifr_flags & IFF_LOOPBACK){
1154
1166
    if(debug){
1155
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1156
 
              if_entry->d_name);
 
1167
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1168
              "Rejecting loopback interface \"%s\"\n", ifname);
1157
1169
    }
1158
 
    return 0;
 
1170
    return false;
1159
1171
  }
1160
1172
  /* Accept point-to-point devices only if connect_to is specified */
1161
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1173
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1162
1174
    if(debug){
1163
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1164
 
              if_entry->d_name);
 
1175
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1176
              "Accepting point-to-point interface \"%s\"\n", ifname);
1165
1177
    }
1166
 
    return 1;
 
1178
    return true;
1167
1179
  }
1168
1180
  /* Otherwise, reject non-broadcast-capable devices */
1169
 
  if(not (flags & IFF_BROADCAST)){
 
1181
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1170
1182
    if(debug){
1171
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1172
 
              if_entry->d_name);
 
1183
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1184
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
1173
1185
    }
1174
 
    return 0;
 
1186
    return false;
1175
1187
  }
1176
1188
  /* Reject non-ARP interfaces (including dummy interfaces) */
1177
 
  if(flags & IFF_NOARP){
 
1189
  if(ifr->ifr_flags & IFF_NOARP){
1178
1190
    if(debug){
1179
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1180
 
              if_entry->d_name);
 
1191
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1192
              "Rejecting non-ARP interface \"%s\"\n", ifname);
1181
1193
    }
1182
 
    return 0;
 
1194
    return false;
1183
1195
  }
 
1196
  
1184
1197
  /* Accept this device */
1185
1198
  if(debug){
1186
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1187
 
            if_entry->d_name);
 
1199
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1200
            "Interface \"%s\" is good\n", ifname);
 
1201
  }
 
1202
  return true;
 
1203
}
 
1204
 
 
1205
/* 
 
1206
 * This function determines if a directory entry in /sys/class/net
 
1207
 * corresponds to an acceptable network device.
 
1208
 * (This function is passed to scandir(3) as a filter function.)
 
1209
 */
 
1210
int good_interface(const struct dirent *if_entry){
 
1211
  if(if_entry->d_name[0] == '.'){
 
1212
    return 0;
 
1213
  }
 
1214
  
 
1215
  struct ifreq ifr;
 
1216
  if(not get_flags(if_entry->d_name, &ifr)){
 
1217
    if(debug){
 
1218
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1219
              "Failed to get flags for interface \"%s\"\n",
 
1220
              if_entry->d_name);
 
1221
    }
 
1222
    return 0;
 
1223
  }
 
1224
  
 
1225
  if(not good_flags(if_entry->d_name, &ifr)){
 
1226
    return 0;
 
1227
  }
 
1228
  return 1;
 
1229
}
 
1230
 
 
1231
/* 
 
1232
 * This function determines if a directory entry in /sys/class/net
 
1233
 * corresponds to an acceptable network device which is up.
 
1234
 * (This function is passed to scandir(3) as a filter function.)
 
1235
 */
 
1236
int up_interface(const struct dirent *if_entry){
 
1237
  if(if_entry->d_name[0] == '.'){
 
1238
    return 0;
 
1239
  }
 
1240
  
 
1241
  struct ifreq ifr;
 
1242
  if(not get_flags(if_entry->d_name, &ifr)){
 
1243
    if(debug){
 
1244
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1245
              "Failed to get flags for interface \"%s\"\n",
 
1246
              if_entry->d_name);
 
1247
    }
 
1248
    return 0;
 
1249
  }
 
1250
  
 
1251
  /* Reject down interfaces */
 
1252
  if(not (ifr.ifr_flags & IFF_UP)){
 
1253
    if(debug){
 
1254
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1255
              "Rejecting down interface \"%s\"\n",
 
1256
              if_entry->d_name);
 
1257
    }
 
1258
    return 0;
 
1259
  }
 
1260
  
 
1261
  /* Reject non-running interfaces */
 
1262
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1263
    if(debug){
 
1264
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1265
              "Rejecting non-running interface \"%s\"\n",
 
1266
              if_entry->d_name);
 
1267
    }
 
1268
    return 0;
 
1269
  }
 
1270
  
 
1271
  if(not good_flags(if_entry->d_name, &ifr)){
 
1272
    return 0;
1188
1273
  }
1189
1274
  return 1;
1190
1275
}
1200
1285
  return 1;
1201
1286
}
1202
1287
 
 
1288
/* Is this directory entry a runnable program? */
 
1289
int runnable_hook(const struct dirent *direntry){
 
1290
  int ret;
 
1291
  size_t sret;
 
1292
  struct stat st;
 
1293
  
 
1294
  if((direntry->d_name)[0] == '\0'){
 
1295
    /* Empty name? */
 
1296
    return 0;
 
1297
  }
 
1298
  
 
1299
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1300
                "abcdefghijklmnopqrstuvwxyz"
 
1301
                "0123456789"
 
1302
                "_-");
 
1303
  if((direntry->d_name)[sret] != '\0'){
 
1304
    /* Contains non-allowed characters */
 
1305
    if(debug){
 
1306
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1307
              "Ignoring hook \"%s\" with bad name\n",
 
1308
              direntry->d_name);
 
1309
    }
 
1310
    return 0;
 
1311
  }
 
1312
  
 
1313
  char *fullname = NULL;
 
1314
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1315
  if(ret < 0){
 
1316
    perror_plus("asprintf");
 
1317
    return 0;
 
1318
  }
 
1319
  
 
1320
  ret = stat(fullname, &st);
 
1321
  if(ret == -1){
 
1322
    if(debug){
 
1323
      perror_plus("Could not stat hook");
 
1324
    }
 
1325
    return 0;
 
1326
  }
 
1327
  if(not (S_ISREG(st.st_mode))){
 
1328
    /* Not a regular file */
 
1329
    if(debug){
 
1330
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1331
              "Ignoring hook \"%s\" - not a file\n",
 
1332
              direntry->d_name);
 
1333
    }
 
1334
    return 0;
 
1335
  }
 
1336
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1337
    /* Not executable */
 
1338
    if(debug){
 
1339
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1340
              "Ignoring hook \"%s\" - not executable\n",
 
1341
              direntry->d_name);
 
1342
    }
 
1343
    return 0;
 
1344
  }
 
1345
  return 1;
 
1346
}
 
1347
 
1203
1348
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1204
1349
  int ret;
1205
1350
  struct timespec now;
1206
1351
  struct timespec waited_time;
1207
1352
  intmax_t block_time;
1208
 
 
 
1353
  
1209
1354
  while(true){
1210
1355
    if(mc.current_server == NULL){
1211
1356
      if (debug){
1212
 
        fprintf(stderr,
 
1357
        fprintf(stderr, "Mandos plugin mandos-client: "
1213
1358
                "Wait until first server is found. No timeout!\n");
1214
1359
      }
1215
1360
      ret = avahi_simple_poll_iterate(s, -1);
1216
1361
    } else {
1217
1362
      if (debug){
1218
 
        fprintf(stderr, "Check current_server if we should run it,"
 
1363
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1364
                "Check current_server if we should run it,"
1219
1365
                " or wait\n");
1220
1366
      }
1221
1367
      /* the current time */
1236
1382
      block_time = ((retry_interval
1237
1383
                     - ((intmax_t)waited_time.tv_sec * 1000))
1238
1384
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1239
 
 
 
1385
      
1240
1386
      if (debug){
1241
 
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1387
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1388
                "Blocking for %" PRIdMAX " ms\n", block_time);
1242
1389
      }
1243
 
 
 
1390
      
1244
1391
      if(block_time <= 0){
1245
1392
        ret = start_mandos_communication(mc.current_server->ip,
1246
1393
                                         mc.current_server->port,
1264
1411
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1265
1412
    }
1266
1413
    if(ret != 0){
1267
 
      if (ret > 0 or errno != EINTR) {
 
1414
      if (ret > 0 or errno != EINTR){
1268
1415
        return (ret != 1) ? ret : 0;
1269
1416
      }
1270
1417
    }
1358
1505
        .arg = "SECONDS",
1359
1506
        .doc = "Retry interval used when denied by the mandos server",
1360
1507
        .group = 2 },
 
1508
      { .name = "network-hook-dir", .key = 133,
 
1509
        .arg = "DIR",
 
1510
        .doc = "Directory where network hooks are located",
 
1511
        .group = 2 },
1361
1512
      /*
1362
1513
       * These reproduce what we would get without ARGP_NO_HELP
1363
1514
       */
1411
1562
        errno = 0;
1412
1563
        retry_interval = strtod(arg, &tmp);
1413
1564
        if(errno != 0 or tmp == arg or *tmp != '\0'
1414
 
           or (retry_interval * 1000) > INT_MAX){
 
1565
           or (retry_interval * 1000) > INT_MAX
 
1566
           or retry_interval < 0){
1415
1567
          argp_error(state, "Bad retry interval");
1416
1568
        }
1417
1569
        break;
 
1570
      case 133:                 /* --network-hook-dir */
 
1571
        hookdir = arg;
 
1572
        break;
1418
1573
        /*
1419
1574
         * These reproduce what we would get without ARGP_NO_HELP
1420
1575
         */
1426
1581
        argp_state_help(state, state->out_stream,
1427
1582
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1428
1583
      case 'V':                 /* --version */
 
1584
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1429
1585
        fprintf(state->out_stream, "%s\n", argp_program_version);
1430
1586
        exit(argp_err_exit_status);
1431
1587
        break;
1455
1611
      goto end;
1456
1612
    }
1457
1613
  }
 
1614
    
 
1615
  {
 
1616
    /* Work around Debian bug #633582:
 
1617
       <http://bugs.debian.org/633582> */
 
1618
    struct stat st;
 
1619
    
 
1620
    /* Re-raise priviliges */
 
1621
    errno = 0;
 
1622
    ret = seteuid(0);
 
1623
    if(ret == -1){
 
1624
      perror_plus("seteuid");
 
1625
    }
 
1626
    
 
1627
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1628
      int seckey_fd = open(seckey, O_RDONLY);
 
1629
      if(seckey_fd == -1){
 
1630
        perror_plus("open");
 
1631
      } else {
 
1632
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1633
        if(ret == -1){
 
1634
          perror_plus("fstat");
 
1635
        } else {
 
1636
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1637
            ret = fchown(seckey_fd, uid, gid);
 
1638
            if(ret == -1){
 
1639
              perror_plus("fchown");
 
1640
            }
 
1641
          }
 
1642
        }
 
1643
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1644
      }
 
1645
    }
 
1646
    
 
1647
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1648
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1649
      if(pubkey_fd == -1){
 
1650
        perror_plus("open");
 
1651
      } else {
 
1652
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1653
        if(ret == -1){
 
1654
          perror_plus("fstat");
 
1655
        } else {
 
1656
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1657
            ret = fchown(pubkey_fd, uid, gid);
 
1658
            if(ret == -1){
 
1659
              perror_plus("fchown");
 
1660
            }
 
1661
          }
 
1662
        }
 
1663
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1664
      }
 
1665
    }
 
1666
    
 
1667
    /* Lower privileges */
 
1668
    errno = 0;
 
1669
    ret = seteuid(uid);
 
1670
    if(ret == -1){
 
1671
      perror_plus("seteuid");
 
1672
    }
 
1673
  }
 
1674
  
 
1675
  /* Find network hooks and run them */
 
1676
  {
 
1677
    struct dirent **direntries;
 
1678
    struct dirent *direntry;
 
1679
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1680
                           alphasort);
 
1681
    if(numhooks == -1){
 
1682
      perror_plus("scandir");
 
1683
    } else {
 
1684
      int devnull = open("/dev/null", O_RDONLY);
 
1685
      for(int i = 0; i < numhooks; i++){
 
1686
        direntry = direntries[0];
 
1687
        char *fullname = NULL;
 
1688
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1689
        if(ret < 0){
 
1690
          perror_plus("asprintf");
 
1691
          continue;
 
1692
        }
 
1693
        pid_t hook_pid = fork();
 
1694
        if(hook_pid == 0){
 
1695
          /* Child */
 
1696
          dup2(devnull, STDIN_FILENO);
 
1697
          close(devnull);
 
1698
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1699
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1700
          if(ret == -1){
 
1701
            perror_plus("setenv");
 
1702
            exit(1);
 
1703
          }
 
1704
          ret = setenv("DEVICE", interface, 1);
 
1705
          if(ret == -1){
 
1706
            perror_plus("setenv");
 
1707
            exit(1);
 
1708
          }
 
1709
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1710
          if(ret == -1){
 
1711
            perror_plus("setenv");
 
1712
            exit(1);
 
1713
          }
 
1714
          ret = setenv("MODE", "start", 1);
 
1715
          if(ret == -1){
 
1716
            perror_plus("setenv");
 
1717
            exit(1);
 
1718
          }
 
1719
          char *delaystring;
 
1720
          ret = asprintf(&delaystring, "%f", delay);
 
1721
          if(ret == -1){
 
1722
            perror_plus("asprintf");
 
1723
            exit(1);
 
1724
          }
 
1725
          ret = setenv("DELAY", delaystring, 1);
 
1726
          if(ret == -1){
 
1727
            free(delaystring);
 
1728
            perror_plus("setenv");
 
1729
            exit(1);
 
1730
          }
 
1731
          free(delaystring);
 
1732
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1733
          perror_plus("execl");
 
1734
        } else {
 
1735
          int status;
 
1736
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1737
            perror_plus("waitpid");
 
1738
            free(fullname);
 
1739
            continue;
 
1740
          }
 
1741
          if(WIFEXITED(status)){
 
1742
            if(WEXITSTATUS(status) != 0){
 
1743
              fprintf(stderr, "Mandos plugin mandos-client: "
 
1744
                      "Warning: network hook \"%s\" exited"
 
1745
                      " with status %d\n", direntry->d_name,
 
1746
                      WEXITSTATUS(status));
 
1747
              free(fullname);
 
1748
              continue;
 
1749
            }
 
1750
          } else if(WIFSIGNALED(status)){
 
1751
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1752
                    "Warning: network hook \"%s\" died by"
 
1753
                    " signal %d\n", direntry->d_name,
 
1754
                    WTERMSIG(status));
 
1755
            free(fullname);
 
1756
            continue;
 
1757
          } else {
 
1758
            fprintf(stderr, "Mandos plugin mandos-client: "
 
1759
                    "Warning: network hook \"%s\" crashed\n",
 
1760
                    direntry->d_name);
 
1761
            free(fullname);
 
1762
            continue;
 
1763
          }
 
1764
        }
 
1765
        free(fullname);
 
1766
        if(quit_now){
 
1767
          goto end;
 
1768
        }
 
1769
      }
 
1770
      close(devnull);
 
1771
    }
 
1772
  }
1458
1773
  
1459
1774
  if(not debug){
1460
1775
    avahi_set_log_function(empty_log);
1461
1776
  }
1462
 
 
 
1777
  
1463
1778
  if(interface[0] == '\0'){
1464
1779
    struct dirent **direntries;
1465
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1780
    /* First look for interfaces that are up */
 
1781
    ret = scandir(sys_class_net, &direntries, up_interface,
1466
1782
                  alphasort);
 
1783
    if(ret == 0){
 
1784
      /* No up interfaces, look for any good interfaces */
 
1785
      free(direntries);
 
1786
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1787
                    alphasort);
 
1788
    }
1467
1789
    if(ret >= 1){
1468
 
      /* Pick the first good interface */
 
1790
      /* Pick the first interface returned */
1469
1791
      interface = strdup(direntries[0]->d_name);
1470
1792
      if(debug){
1471
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1793
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1794
                "Using interface \"%s\"\n", interface);
1472
1795
      }
1473
1796
      if(interface == NULL){
1474
1797
        perror_plus("malloc");
1479
1802
      free(direntries);
1480
1803
    } else {
1481
1804
      free(direntries);
1482
 
      fprintf(stderr, "Could not find a network interface\n");
 
1805
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1806
              "Could not find a network interface\n");
1483
1807
      exitcode = EXIT_FAILURE;
1484
1808
      goto end;
1485
1809
    }
1491
1815
  srand((unsigned int) time(NULL));
1492
1816
  mc.simple_poll = avahi_simple_poll_new();
1493
1817
  if(mc.simple_poll == NULL){
1494
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1818
    fprintf(stderr, "Mandos plugin mandos-client: "
 
1819
            "Avahi: Failed to create simple poll object.\n");
1495
1820
    exitcode = EX_UNAVAILABLE;
1496
1821
    goto end;
1497
1822
  }
1563
1888
  if(strcmp(interface, "none") != 0){
1564
1889
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1565
1890
    if(if_index == 0){
1566
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1891
      fprintf(stderr, "Mandos plugin mandos-client: "
 
1892
              "No such interface: \"%s\"\n", interface);
1567
1893
      exitcode = EX_UNAVAILABLE;
1568
1894
      goto end;
1569
1895
    }
1710
2036
  
1711
2037
  ret = init_gnutls_global(pubkey, seckey);
1712
2038
  if(ret == -1){
1713
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2039
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2040
            "init_gnutls_global failed\n");
1714
2041
    exitcode = EX_UNAVAILABLE;
1715
2042
    goto end;
1716
2043
  } else {
1732
2059
  }
1733
2060
  
1734
2061
  if(not init_gpgme(pubkey, seckey, tempdir)){
1735
 
    fprintf(stderr, "init_gpgme failed\n");
 
2062
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2063
            "init_gpgme failed\n");
1736
2064
    exitcode = EX_UNAVAILABLE;
1737
2065
    goto end;
1738
2066
  } else {
1748
2076
    /* (Mainly meant for debugging) */
1749
2077
    char *address = strrchr(connect_to, ':');
1750
2078
    if(address == NULL){
1751
 
      fprintf(stderr, "No colon in address\n");
 
2079
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2080
              "No colon in address\n");
1752
2081
      exitcode = EX_USAGE;
1753
2082
      goto end;
1754
2083
    }
1762
2091
    tmpmax = strtoimax(address+1, &tmp, 10);
1763
2092
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1764
2093
       or tmpmax != (uint16_t)tmpmax){
1765
 
      fprintf(stderr, "Bad port number\n");
 
2094
      fprintf(stderr, "Mandos plugin mandos-client: "
 
2095
              "Bad port number\n");
1766
2096
      exitcode = EX_USAGE;
1767
2097
      goto end;
1768
2098
    }
1773
2103
    
1774
2104
    port = (uint16_t)tmpmax;
1775
2105
    *address = '\0';
1776
 
    address = connect_to;
1777
2106
    /* Colon in address indicates IPv6 */
1778
2107
    int af;
1779
 
    if(strchr(address, ':') != NULL){
 
2108
    if(strchr(connect_to, ':') != NULL){
1780
2109
      af = AF_INET6;
 
2110
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2111
      if(connect_to[0] == '[' and address[-1] == ']')
 
2112
        {
 
2113
          connect_to++;
 
2114
          address[-1] = '\0';
 
2115
        }
1781
2116
    } else {
1782
2117
      af = AF_INET;
1783
2118
    }
 
2119
    address = connect_to;
1784
2120
    
1785
2121
    if(quit_now){
1786
2122
      goto end;
1787
2123
    }
1788
 
 
 
2124
    
1789
2125
    while(not quit_now){
1790
2126
      ret = start_mandos_communication(address, port, if_index, af);
1791
2127
      if(quit_now or ret == 0){
1792
2128
        break;
1793
2129
      }
1794
 
      sleep((int)retry_interval or 1);
1795
 
    };
1796
 
 
 
2130
      if(debug){
 
2131
        fprintf(stderr, "Mandos plugin mandos-client: "
 
2132
                "Retrying in %d seconds\n", (int)retry_interval);
 
2133
      }
 
2134
      sleep((int)retry_interval);
 
2135
    }
 
2136
    
1797
2137
    if (not quit_now){
1798
2138
      exitcode = EXIT_SUCCESS;
1799
2139
    }
1800
 
 
 
2140
    
1801
2141
    goto end;
1802
2142
  }
1803
2143
  
1825
2165
  
1826
2166
  /* Check if creating the Avahi server object succeeded */
1827
2167
  if(mc.server == NULL){
1828
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2168
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2169
            "Failed to create Avahi server: %s\n",
1829
2170
            avahi_strerror(error));
1830
2171
    exitcode = EX_UNAVAILABLE;
1831
2172
    goto end;
1840
2181
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1841
2182
                                   NULL, 0, browse_callback, NULL);
1842
2183
  if(sb == NULL){
1843
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2184
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2185
            "Failed to create service browser: %s\n",
1844
2186
            avahi_strerror(avahi_server_errno(mc.server)));
1845
2187
    exitcode = EX_UNAVAILABLE;
1846
2188
    goto end;
1853
2195
  /* Run the main loop */
1854
2196
  
1855
2197
  if(debug){
1856
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2198
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2199
            "Starting Avahi loop search\n");
1857
2200
  }
1858
2201
 
1859
2202
  ret = avahi_loop_with_timeout(mc.simple_poll,
1860
2203
                                (int)(retry_interval * 1000));
1861
2204
  if(debug){
1862
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2205
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2206
            "avahi_loop_with_timeout exited %s\n",
1863
2207
            (ret == 0) ? "successfully" : "with error");
1864
2208
  }
1865
2209
  
1866
2210
 end:
1867
2211
  
1868
2212
  if(debug){
1869
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2213
    fprintf(stderr, "Mandos plugin mandos-client: "
 
2214
            "%s exiting\n", argv[0]);
1870
2215
  }
1871
2216
  
1872
2217
  /* Cleanup things */
1900
2245
    }
1901
2246
  }
1902
2247
  
 
2248
  /* XXX run network hooks "stop" here  */
 
2249
  
1903
2250
  /* Take down the network interface */
1904
2251
  if(take_down_interface){
1905
2252
    /* Re-raise priviliges */
1912
2259
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1913
2260
      if(ret == -1){
1914
2261
        perror_plus("ioctl SIOCGIFFLAGS");
1915
 
      } else if(network.ifr_flags & IFF_UP) {
 
2262
      } else if(network.ifr_flags & IFF_UP){
1916
2263
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1917
2264
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1918
2265
        if(ret == -1){
1936
2283
  if(tempdir_created){
1937
2284
    struct dirent **direntries = NULL;
1938
2285
    struct dirent *direntry = NULL;
1939
 
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
1940
 
    if (ret > 0){
1941
 
      for(int i = 0; i < ret; i++){
 
2286
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2287
                             alphasort);
 
2288
    if (numentries > 0){
 
2289
      for(int i = 0; i < numentries; i++){
1942
2290
        direntry = direntries[i];
1943
2291
        char *fullname = NULL;
1944
2292
        ret = asprintf(&fullname, "%s/%s", tempdir,
1949
2297
        }
1950
2298
        ret = remove(fullname);
1951
2299
        if(ret == -1){
1952
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1953
 
                  strerror(errno));
 
2300
          fprintf(stderr, "Mandos plugin mandos-client: "
 
2301
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
1954
2302
        }
1955
2303
        free(fullname);
1956
2304
      }
1957
2305
    }
1958
2306
 
1959
 
    /* need to be cleaned even if ret == 0 because man page doesn't
1960
 
       specify */
 
2307
    /* need to clean even if 0 because man page doesn't specify */
1961
2308
    free(direntries);
1962
 
    if (ret == -1){
 
2309
    if (numentries == -1){
1963
2310
      perror_plus("scandir");
1964
2311
    }
1965
2312
    ret = rmdir(tempdir);