/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-07-25 18:52:11 UTC
  • mfrom: (489 trunk)
  • mto: (237.4.29 release)
  • mto: This revision was merged to the branch mainline in revision 490.
  • Revision ID: teddy@fukt.bsnet.se-20110725185211-wlitr9jvs70e1xh8
MergeĀ fromĀ trunk.

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() */
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() */
90
88
 
91
89
#ifdef __linux__
92
90
#include <sys/klog.h>           /* klogctl() */
110
108
                                   init_gnutls_session(),
111
109
                                   GNUTLS_* */
112
110
#include <gnutls/openpgp.h>
113
 
                         /* gnutls_certificate_set_openpgp_key_file(),
114
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
 
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
115
113
 
116
114
/* GPGME */
117
115
#include <gpgme.h>              /* All GPGME types, constants and
125
123
#define PATHDIR "/conf/conf.d/mandos"
126
124
#define SECKEY "seckey.txt"
127
125
#define PUBKEY "pubkey.txt"
128
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
129
126
 
130
127
bool debug = false;
131
128
static const char mandos_protocol_version[] = "1";
132
129
const char *argp_program_version = "mandos-client " VERSION;
133
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
130
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
134
131
static const char sys_class_net[] = "/sys/class/net";
135
132
char *connect_to = NULL;
136
 
const char *hookdir = HOOKDIR;
137
133
 
138
134
/* Doubly linked list that need to be circularly linked when used */
139
135
typedef struct server{
174
170
  perror(print_text);
175
171
}
176
172
 
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
 
 
185
173
/*
186
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
187
175
 * bytes. "buffer_capacity" is how much is currently allocated,
188
176
 * "buffer_length" is how much is already used.
189
177
 */
190
178
size_t incbuffer(char **buffer, size_t buffer_length,
191
 
                 size_t buffer_capacity){
 
179
                  size_t buffer_capacity){
192
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
193
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
194
182
    if(buffer == NULL){
199
187
  return buffer_capacity;
200
188
}
201
189
 
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){
 
190
int add_server(const char *ip, uint16_t port,
 
191
                 AvahiIfIndex if_index,
 
192
                 int af){
205
193
  int ret;
206
194
  server *new_server = malloc(sizeof(server));
207
195
  if(new_server == NULL){
209
197
    return -1;
210
198
  }
211
199
  *new_server = (server){ .ip = strdup(ip),
212
 
                          .port = port,
213
 
                          .if_index = if_index,
214
 
                          .af = af };
 
200
                         .port = port,
 
201
                         .if_index = if_index,
 
202
                         .af = af };
215
203
  if(new_server->ip == NULL){
216
204
    perror_plus("strdup");
217
205
    return -1;
218
206
  }
219
 
  /* Special case of first server */
 
207
  /* unique case of first server */
220
208
  if (mc.current_server == NULL){
221
209
    new_server->next = new_server;
222
210
    new_server->prev = new_server;
223
211
    mc.current_server = new_server;
224
 
  /* Place the new server last in the list */
 
212
  /* Placing the new server last in the list */
225
213
  } else {
226
214
    new_server->next = mc.current_server;
227
215
    new_server->prev = mc.current_server->prev;
239
227
/* 
240
228
 * Initialize GPGME.
241
229
 */
242
 
static bool init_gpgme(const char *seckey, const char *pubkey,
243
 
                       const char *tempdir){
 
230
static bool init_gpgme(const char *seckey,
 
231
                       const char *pubkey, const char *tempdir){
244
232
  gpgme_error_t rc;
245
233
  gpgme_engine_info_t engine_info;
246
234
  
261
249
    
262
250
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
263
251
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
252
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
266
253
              gpgme_strsource(rc), gpgme_strerror(rc));
267
254
      return false;
268
255
    }
269
256
    
270
257
    rc = gpgme_op_import(mc.ctx, pgp_data);
271
258
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf(stderr, "Mandos plugin mandos-client: "
273
 
              "bad gpgme_op_import: %s: %s\n",
 
259
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
274
260
              gpgme_strsource(rc), gpgme_strerror(rc));
275
261
      return false;
276
262
    }
284
270
  }
285
271
  
286
272
  if(debug){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "Initializing GPGME\n");
 
273
    fprintf(stderr, "Initializing GPGME\n");
289
274
  }
290
275
  
291
276
  /* Init GPGME */
292
277
  gpgme_check_version(NULL);
293
278
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
294
279
  if(rc != GPG_ERR_NO_ERROR){
295
 
    fprintf(stderr, "Mandos plugin mandos-client: "
296
 
            "bad gpgme_engine_check_version: %s: %s\n",
 
280
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
297
281
            gpgme_strsource(rc), gpgme_strerror(rc));
298
282
    return false;
299
283
  }
300
284
  
301
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
285
    /* Set GPGME home directory for the OpenPGP engine only */
302
286
  rc = gpgme_get_engine_info(&engine_info);
303
287
  if(rc != GPG_ERR_NO_ERROR){
304
 
    fprintf(stderr, "Mandos plugin mandos-client: "
305
 
            "bad gpgme_get_engine_info: %s: %s\n",
 
288
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
306
289
            gpgme_strsource(rc), gpgme_strerror(rc));
307
290
    return false;
308
291
  }
315
298
    engine_info = engine_info->next;
316
299
  }
317
300
  if(engine_info == NULL){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
301
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
320
302
    return false;
321
303
  }
322
304
  
323
305
  /* Create new GPGME "context" */
324
306
  rc = gpgme_new(&(mc.ctx));
325
307
  if(rc != GPG_ERR_NO_ERROR){
326
 
    fprintf(stderr, "Mandos plugin mandos-client: "
327
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
328
 
            gpgme_strerror(rc));
 
308
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
309
            gpgme_strsource(rc), gpgme_strerror(rc));
329
310
    return false;
330
311
  }
331
312
  
350
331
  ssize_t plaintext_length = 0;
351
332
  
352
333
  if(debug){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "Trying to decrypt OpenPGP data\n");
 
334
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
355
335
  }
356
336
  
357
337
  /* Create new GPGME data buffer from memory cryptotext */
358
338
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
359
339
                               0);
360
340
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "Mandos plugin mandos-client: "
362
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
341
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
363
342
            gpgme_strsource(rc), gpgme_strerror(rc));
364
343
    return -1;
365
344
  }
367
346
  /* Create new empty GPGME data buffer for the plaintext */
368
347
  rc = gpgme_data_new(&dh_plain);
369
348
  if(rc != GPG_ERR_NO_ERROR){
370
 
    fprintf(stderr, "Mandos plugin mandos-client: "
371
 
            "bad gpgme_data_new: %s: %s\n",
 
349
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
372
350
            gpgme_strsource(rc), gpgme_strerror(rc));
373
351
    gpgme_data_release(dh_crypto);
374
352
    return -1;
378
356
     data buffer */
379
357
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
380
358
  if(rc != GPG_ERR_NO_ERROR){
381
 
    fprintf(stderr, "Mandos plugin mandos-client: "
382
 
            "bad gpgme_op_decrypt: %s: %s\n",
 
359
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
383
360
            gpgme_strsource(rc), gpgme_strerror(rc));
384
361
    plaintext_length = -1;
385
362
    if(debug){
386
363
      gpgme_decrypt_result_t result;
387
364
      result = gpgme_op_decrypt_result(mc.ctx);
388
365
      if(result == NULL){
389
 
        fprintf(stderr, "Mandos plugin mandos-client: "
390
 
                "gpgme_op_decrypt_result failed\n");
 
366
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
391
367
      } else {
392
 
        fprintf(stderr, "Mandos plugin mandos-client: "
393
 
                "Unsupported algorithm: %s\n",
 
368
        fprintf(stderr, "Unsupported algorithm: %s\n",
394
369
                result->unsupported_algorithm);
395
 
        fprintf(stderr, "Mandos plugin mandos-client: "
396
 
                "Wrong key usage: %u\n",
 
370
        fprintf(stderr, "Wrong key usage: %u\n",
397
371
                result->wrong_key_usage);
398
372
        if(result->file_name != NULL){
399
 
          fprintf(stderr, "Mandos plugin mandos-client: "
400
 
                  "File name: %s\n", result->file_name);
 
373
          fprintf(stderr, "File name: %s\n", result->file_name);
401
374
        }
402
375
        gpgme_recipient_t recipient;
403
376
        recipient = result->recipients;
404
377
        while(recipient != NULL){
405
 
          fprintf(stderr, "Mandos plugin mandos-client: "
406
 
                  "Public key algorithm: %s\n",
 
378
          fprintf(stderr, "Public key algorithm: %s\n",
407
379
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
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",
 
380
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
381
          fprintf(stderr, "Secret key available: %s\n",
412
382
                  recipient->status == GPG_ERR_NO_SECKEY
413
383
                  ? "No" : "Yes");
414
384
          recipient = recipient->next;
419
389
  }
420
390
  
421
391
  if(debug){
422
 
    fprintf(stderr, "Mandos plugin mandos-client: "
423
 
            "Decryption of OpenPGP data succeeded\n");
 
392
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
424
393
  }
425
394
  
426
395
  /* Seek back to the beginning of the GPGME plaintext data buffer */
433
402
  *plaintext = NULL;
434
403
  while(true){
435
404
    plaintext_capacity = incbuffer(plaintext,
436
 
                                   (size_t)plaintext_length,
437
 
                                   plaintext_capacity);
 
405
                                      (size_t)plaintext_length,
 
406
                                      plaintext_capacity);
438
407
    if(plaintext_capacity == 0){
439
 
      perror_plus("incbuffer");
440
 
      plaintext_length = -1;
441
 
      goto decrypt_end;
 
408
        perror_plus("incbuffer");
 
409
        plaintext_length = -1;
 
410
        goto decrypt_end;
442
411
    }
443
412
    
444
413
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
457
426
  }
458
427
  
459
428
  if(debug){
460
 
    fprintf(stderr, "Mandos plugin mandos-client: "
461
 
            "Decrypted password is: ");
 
429
    fprintf(stderr, "Decrypted password is: ");
462
430
    for(ssize_t i = 0; i < plaintext_length; i++){
463
431
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
464
432
    }
486
454
/* GnuTLS log function callback */
487
455
static void debuggnutls(__attribute__((unused)) int level,
488
456
                        const char* string){
489
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
457
  fprintf(stderr, "GnuTLS: %s", string);
490
458
}
491
459
 
492
460
static int init_gnutls_global(const char *pubkeyfilename,
494
462
  int ret;
495
463
  
496
464
  if(debug){
497
 
    fprintf(stderr, "Mandos plugin mandos-client: "
498
 
            "Initializing GnuTLS\n");
 
465
    fprintf(stderr, "Initializing GnuTLS\n");
499
466
  }
500
467
  
501
468
  ret = gnutls_global_init();
502
469
  if(ret != GNUTLS_E_SUCCESS){
503
 
    fprintf(stderr, "Mandos plugin mandos-client: "
504
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
470
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
471
            safer_gnutls_strerror(ret));
505
472
    return -1;
506
473
  }
507
474
  
516
483
  /* OpenPGP credentials */
517
484
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
518
485
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Mandos plugin mandos-client: "
520
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
486
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
487
            safer_gnutls_strerror(ret));
521
488
    gnutls_global_deinit();
522
489
    return -1;
523
490
  }
524
491
  
525
492
  if(debug){
526
 
    fprintf(stderr, "Mandos plugin mandos-client: "
527
 
            "Attempting to use OpenPGP public key %s and"
 
493
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
528
494
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
529
495
            seckeyfilename);
530
496
  }
534
500
     GNUTLS_OPENPGP_FMT_BASE64);
535
501
  if(ret != GNUTLS_E_SUCCESS){
536
502
    fprintf(stderr,
537
 
            "Mandos plugin mandos-client: "
538
503
            "Error[%d] while reading the OpenPGP key pair ('%s',"
539
504
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
505
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
506
            safer_gnutls_strerror(ret));
542
507
    goto globalfail;
543
508
  }
544
509
  
545
510
  /* GnuTLS server initialization */
546
511
  ret = gnutls_dh_params_init(&mc.dh_params);
547
512
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Mandos plugin mandos-client: "
549
 
            "Error in GnuTLS DH parameter initialization:"
 
513
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
550
514
            " %s\n", safer_gnutls_strerror(ret));
551
515
    goto globalfail;
552
516
  }
553
517
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
554
518
  if(ret != GNUTLS_E_SUCCESS){
555
 
    fprintf(stderr, "Mandos plugin mandos-client: "
556
 
            "Error in GnuTLS prime generation: %s\n",
 
519
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
557
520
            safer_gnutls_strerror(ret));
558
521
    goto globalfail;
559
522
  }
580
543
    }
581
544
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
582
545
  if(ret != GNUTLS_E_SUCCESS){
583
 
    fprintf(stderr, "Mandos plugin mandos-client: "
584
 
            "Error in GnuTLS session initialization: %s\n",
 
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
585
547
            safer_gnutls_strerror(ret));
586
548
  }
587
549
  
595
557
      }
596
558
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
597
559
    if(ret != GNUTLS_E_SUCCESS){
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));
 
560
      fprintf(stderr, "Syntax error at: %s\n", err);
 
561
      fprintf(stderr, "GnuTLS error: %s\n",
 
562
              safer_gnutls_strerror(ret));
602
563
      gnutls_deinit(*session);
603
564
      return -1;
604
565
    }
613
574
    }
614
575
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
615
576
  if(ret != GNUTLS_E_SUCCESS){
616
 
    fprintf(stderr, "Mandos plugin mandos-client: "
617
 
            "Error setting GnuTLS credentials: %s\n",
 
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
618
578
            safer_gnutls_strerror(ret));
619
579
    gnutls_deinit(*session);
620
580
    return -1;
666
626
    pf = PF_INET;
667
627
    break;
668
628
  default:
669
 
    fprintf(stderr, "Mandos plugin mandos-client: "
670
 
            "Bad address family: %d\n", af);
 
629
    fprintf(stderr, "Bad address family: %d\n", af);
671
630
    errno = EINVAL;
672
631
    return -1;
673
632
  }
678
637
  }
679
638
  
680
639
  if(debug){
681
 
    fprintf(stderr, "Mandos plugin mandos-client: "
682
 
            "Setting up a TCP connection to %s, port %" PRIu16
 
640
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
683
641
            "\n", ip, port);
684
642
  }
685
643
  
712
670
  }
713
671
  if(ret == 0){
714
672
    int e = errno;
715
 
    fprintf(stderr, "Mandos plugin mandos-client: "
716
 
            "Bad address: %s\n", ip);
 
673
    fprintf(stderr, "Bad address: %s\n", ip);
717
674
    errno = e;
718
675
    goto mandos_end;
719
676
  }
724
681
    
725
682
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
726
683
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
727
 
                                -Wunreachable-code*/
 
684
                              -Wunreachable-code*/
728
685
      if(if_index == AVAHI_IF_UNSPEC){
729
 
        fprintf(stderr, "Mandos plugin mandos-client: "
730
 
                "An IPv6 link-local address is incomplete"
 
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
731
687
                " without a network interface\n");
732
688
        errno = EINVAL;
733
689
        goto mandos_end;
752
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
753
709
        perror_plus("if_indextoname");
754
710
      } else {
755
 
        fprintf(stderr, "Mandos plugin mandos-client: "
756
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
757
712
                ip, interface, port);
758
713
      }
759
714
    } else {
760
 
      fprintf(stderr, "Mandos plugin mandos-client: "
761
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
715
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
716
              port);
762
717
    }
763
718
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
764
719
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
774
729
      perror_plus("inet_ntop");
775
730
    } else {
776
731
      if(strcmp(addrstr, ip) != 0){
777
 
        fprintf(stderr, "Mandos plugin mandos-client: "
778
 
                "Canonical address form: %s\n", addrstr);
 
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
779
733
      }
780
734
    }
781
735
  }
809
763
  while(true){
810
764
    size_t out_size = strlen(out);
811
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
812
 
                                        out_size - written));
 
766
                                   out_size - written));
813
767
    if(ret == -1){
814
768
      int e = errno;
815
769
      perror_plus("write");
835
789
  }
836
790
  
837
791
  if(debug){
838
 
    fprintf(stderr, "Mandos plugin mandos-client: "
839
 
            "Establishing TLS session with %s\n", ip);
 
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
840
793
  }
841
794
  
842
795
  if(quit_now){
862
815
  
863
816
  if(ret != GNUTLS_E_SUCCESS){
864
817
    if(debug){
865
 
      fprintf(stderr, "Mandos plugin mandos-client: "
866
 
              "*** GnuTLS Handshake failed ***\n");
 
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
867
819
      gnutls_perror(ret);
868
820
    }
869
821
    errno = EPROTO;
873
825
  /* Read OpenPGP packet that contains the wanted password */
874
826
  
875
827
  if(debug){
876
 
    fprintf(stderr, "Mandos plugin mandos-client: "
877
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
828
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
829
            ip);
878
830
  }
879
831
  
880
832
  while(true){
885
837
    }
886
838
    
887
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
888
 
                                buffer_capacity);
 
840
                                   buffer_capacity);
889
841
    if(buffer_capacity == 0){
890
842
      int e = errno;
891
843
      perror_plus("incbuffer");
918
870
          }
919
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
920
872
        if(ret < 0){
921
 
          fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
923
874
          gnutls_perror(ret);
924
875
          errno = EPROTO;
925
876
          goto mandos_end;
926
877
        }
927
878
        break;
928
879
      default:
929
 
        fprintf(stderr, "Mandos plugin mandos-client: "
930
 
                "Unknown error while reading data from"
 
880
        fprintf(stderr, "Unknown error while reading data from"
931
881
                " encrypted session with Mandos server\n");
932
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
933
883
        errno = EIO;
939
889
  }
940
890
  
941
891
  if(debug){
942
 
    fprintf(stderr, "Mandos plugin mandos-client: "
943
 
            "Closing TLS session\n");
 
892
    fprintf(stderr, "Closing TLS session\n");
944
893
  }
945
894
  
946
895
  if(quit_now){
958
907
  
959
908
  if(buffer_length > 0){
960
909
    ssize_t decrypted_buffer_size;
961
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
911
                                               buffer_length,
962
912
                                               &decrypted_buffer);
963
913
    if(decrypted_buffer_size >= 0){
964
914
      
975
925
        if(ret == 0 and ferror(stdout)){
976
926
          int e = errno;
977
927
          if(debug){
978
 
            fprintf(stderr, "Mandos plugin mandos-client: "
979
 
                    "Error writing encrypted data: %s\n",
 
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
980
929
                    strerror(errno));
981
930
          }
982
931
          errno = e;
1040
989
  switch(event){
1041
990
  default:
1042
991
  case AVAHI_RESOLVER_FAILURE:
1043
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1044
 
            "(Avahi Resolver) Failed to resolve service '%s'"
 
992
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
1045
993
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1046
994
            avahi_strerror(avahi_server_errno(mc.server)));
1047
995
    break;
1051
999
      char ip[AVAHI_ADDRESS_STR_MAX];
1052
1000
      avahi_address_snprint(ip, sizeof(ip), address);
1053
1001
      if(debug){
1054
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1055
 
                "Mandos server \"%s\" found on %s (%s, %"
 
1002
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1056
1003
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1057
1004
                ip, (intmax_t)interface, port);
1058
1005
      }
1092
1039
  default:
1093
1040
  case AVAHI_BROWSER_FAILURE:
1094
1041
    
1095
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1096
 
            "(Avahi browser) %s\n",
 
1042
    fprintf(stderr, "(Avahi browser) %s\n",
1097
1043
            avahi_strerror(avahi_server_errno(mc.server)));
1098
1044
    avahi_simple_poll_quit(mc.simple_poll);
1099
1045
    return;
1107
1053
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1108
1054
                                    name, type, domain, protocol, 0,
1109
1055
                                    resolve_callback, NULL) == NULL)
1110
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1111
 
              "Avahi: Failed to resolve service '%s': %s\n",
 
1056
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1112
1057
              name, avahi_strerror(avahi_server_errno(mc.server)));
1113
1058
    break;
1114
1059
    
1118
1063
  case AVAHI_BROWSER_ALL_FOR_NOW:
1119
1064
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1120
1065
    if(debug){
1121
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1122
 
              "No Mandos server found, still searching...\n");
 
1066
      fprintf(stderr, "No Mandos server found, still searching...\n");
1123
1067
    }
1124
1068
    break;
1125
1069
  }
1140
1084
  errno = old_errno;
1141
1085
}
1142
1086
 
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){
 
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){
1154
1143
    if(debug){
1155
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1144
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1145
              flagstring, if_entry->d_name);
1156
1146
    }
1157
 
    return false;
 
1147
    free(flagstring);
 
1148
    return 0;
1158
1149
  }
1159
 
  return true;
1160
 
}
1161
 
 
1162
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1163
 
  
 
1150
  free(flagstring);
 
1151
  ifreq_flags flags = (ifreq_flags)tmpmax;
1164
1152
  /* Reject the loopback device */
1165
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1153
  if(flags & IFF_LOOPBACK){
1166
1154
    if(debug){
1167
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1168
 
              "Rejecting loopback interface \"%s\"\n", ifname);
 
1155
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
              if_entry->d_name);
1169
1157
    }
1170
 
    return false;
 
1158
    return 0;
1171
1159
  }
1172
1160
  /* Accept point-to-point devices only if connect_to is specified */
1173
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1161
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1174
1162
    if(debug){
1175
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1176
 
              "Accepting point-to-point interface \"%s\"\n", ifname);
 
1163
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1164
              if_entry->d_name);
1177
1165
    }
1178
 
    return true;
 
1166
    return 1;
1179
1167
  }
1180
1168
  /* Otherwise, reject non-broadcast-capable devices */
1181
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1169
  if(not (flags & IFF_BROADCAST)){
1182
1170
    if(debug){
1183
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1184
 
              "Rejecting non-broadcast interface \"%s\"\n", ifname);
 
1171
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1172
              if_entry->d_name);
1185
1173
    }
1186
 
    return false;
 
1174
    return 0;
1187
1175
  }
1188
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
1189
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1177
  if(flags & IFF_NOARP){
1190
1178
    if(debug){
1191
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1192
 
              "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1179
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
              if_entry->d_name);
1193
1181
    }
1194
 
    return false;
 
1182
    return 0;
1195
1183
  }
1196
 
  
1197
1184
  /* Accept this device */
1198
1185
  if(debug){
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;
 
1186
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1187
            if_entry->d_name);
1273
1188
  }
1274
1189
  return 1;
1275
1190
}
1285
1200
  return 1;
1286
1201
}
1287
1202
 
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
 
 
1348
1203
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1349
1204
  int ret;
1350
1205
  struct timespec now;
1351
1206
  struct timespec waited_time;
1352
1207
  intmax_t block_time;
1353
 
  
 
1208
 
1354
1209
  while(true){
1355
1210
    if(mc.current_server == NULL){
1356
1211
      if (debug){
1357
 
        fprintf(stderr, "Mandos plugin mandos-client: "
 
1212
        fprintf(stderr,
1358
1213
                "Wait until first server is found. No timeout!\n");
1359
1214
      }
1360
1215
      ret = avahi_simple_poll_iterate(s, -1);
1361
1216
    } else {
1362
1217
      if (debug){
1363
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1364
 
                "Check current_server if we should run it,"
 
1218
        fprintf(stderr, "Check current_server if we should run it,"
1365
1219
                " or wait\n");
1366
1220
      }
1367
1221
      /* the current time */
1382
1236
      block_time = ((retry_interval
1383
1237
                     - ((intmax_t)waited_time.tv_sec * 1000))
1384
1238
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1385
 
      
 
1239
 
1386
1240
      if (debug){
1387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1388
 
                "Blocking for %" PRIdMAX " ms\n", block_time);
 
1241
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
1389
1242
      }
1390
 
      
 
1243
 
1391
1244
      if(block_time <= 0){
1392
1245
        ret = start_mandos_communication(mc.current_server->ip,
1393
1246
                                         mc.current_server->port,
1411
1264
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1412
1265
    }
1413
1266
    if(ret != 0){
1414
 
      if (ret > 0 or errno != EINTR){
 
1267
      if (ret > 0 or errno != EINTR) {
1415
1268
        return (ret != 1) ? ret : 0;
1416
1269
      }
1417
1270
    }
1505
1358
        .arg = "SECONDS",
1506
1359
        .doc = "Retry interval used when denied by the mandos server",
1507
1360
        .group = 2 },
1508
 
      { .name = "network-hook-dir", .key = 133,
1509
 
        .arg = "DIR",
1510
 
        .doc = "Directory where network hooks are located",
1511
 
        .group = 2 },
1512
1361
      /*
1513
1362
       * These reproduce what we would get without ARGP_NO_HELP
1514
1363
       */
1562
1411
        errno = 0;
1563
1412
        retry_interval = strtod(arg, &tmp);
1564
1413
        if(errno != 0 or tmp == arg or *tmp != '\0'
1565
 
           or (retry_interval * 1000) > INT_MAX
1566
 
           or retry_interval < 0){
 
1414
           or (retry_interval * 1000) > INT_MAX){
1567
1415
          argp_error(state, "Bad retry interval");
1568
1416
        }
1569
1417
        break;
1570
 
      case 133:                 /* --network-hook-dir */
1571
 
        hookdir = arg;
1572
 
        break;
1573
1418
        /*
1574
1419
         * These reproduce what we would get without ARGP_NO_HELP
1575
1420
         */
1581
1426
        argp_state_help(state, state->out_stream,
1582
1427
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1583
1428
      case 'V':                 /* --version */
1584
 
        fprintf(state->out_stream, "Mandos plugin mandos-client: ");
1585
1429
        fprintf(state->out_stream, "%s\n", argp_program_version);
1586
1430
        exit(argp_err_exit_status);
1587
1431
        break;
1624
1468
      perror_plus("seteuid");
1625
1469
    }
1626
1470
    
1627
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1628
 
      int seckey_fd = open(seckey, O_RDONLY);
1629
 
      if(seckey_fd == -1){
1630
 
        perror_plus("open");
 
1471
    int seckey_fd = open(PATHDIR "/" SECKEY, O_RDONLY);
 
1472
    if(seckey_fd == -1){
 
1473
      perror_plus("open");
 
1474
    } else {
 
1475
      ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1476
      if(ret == -1){
 
1477
        perror_plus("fstat");
1631
1478
      } 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
 
            }
 
1479
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1480
          ret = fchown(seckey_fd, uid, gid);
 
1481
          if(ret == -1){
 
1482
            perror_plus("fchown");
1641
1483
          }
1642
1484
        }
1643
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1644
1485
      }
 
1486
      TEMP_FAILURE_RETRY(close(seckey_fd));
1645
1487
    }
1646
1488
    
1647
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1648
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1649
 
      if(pubkey_fd == -1){
1650
 
        perror_plus("open");
 
1489
    int pubkey_fd = open(PATHDIR "/" PUBKEY, O_RDONLY);
 
1490
    if(pubkey_fd == -1){
 
1491
      perror_plus("open");
 
1492
    } else {
 
1493
      ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1494
      if(ret == -1){
 
1495
        perror_plus("fstat");
1651
1496
      } 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
 
            }
 
1497
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1498
          ret = fchown(pubkey_fd, uid, gid);
 
1499
          if(ret == -1){
 
1500
            perror_plus("fchown");
1661
1501
          }
1662
1502
        }
1663
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1664
1503
      }
 
1504
      TEMP_FAILURE_RETRY(close(pubkey_fd));
1665
1505
    }
1666
1506
    
1667
1507
    /* Lower privileges */
1672
1512
    }
1673
1513
  }
1674
1514
  
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
 
  }
1773
 
  
1774
1515
  if(not debug){
1775
1516
    avahi_set_log_function(empty_log);
1776
1517
  }
1777
 
  
 
1518
 
1778
1519
  if(interface[0] == '\0'){
1779
1520
    struct dirent **direntries;
1780
 
    /* First look for interfaces that are up */
1781
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1521
    ret = scandir(sys_class_net, &direntries, good_interface,
1782
1522
                  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
 
    }
1789
1523
    if(ret >= 1){
1790
 
      /* Pick the first interface returned */
 
1524
      /* Pick the first good interface */
1791
1525
      interface = strdup(direntries[0]->d_name);
1792
1526
      if(debug){
1793
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1794
 
                "Using interface \"%s\"\n", interface);
 
1527
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1795
1528
      }
1796
1529
      if(interface == NULL){
1797
1530
        perror_plus("malloc");
1802
1535
      free(direntries);
1803
1536
    } else {
1804
1537
      free(direntries);
1805
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1806
 
              "Could not find a network interface\n");
 
1538
      fprintf(stderr, "Could not find a network interface\n");
1807
1539
      exitcode = EXIT_FAILURE;
1808
1540
      goto end;
1809
1541
    }
1815
1547
  srand((unsigned int) time(NULL));
1816
1548
  mc.simple_poll = avahi_simple_poll_new();
1817
1549
  if(mc.simple_poll == NULL){
1818
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1819
 
            "Avahi: Failed to create simple poll object.\n");
 
1550
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1820
1551
    exitcode = EX_UNAVAILABLE;
1821
1552
    goto end;
1822
1553
  }
1888
1619
  if(strcmp(interface, "none") != 0){
1889
1620
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1890
1621
    if(if_index == 0){
1891
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1892
 
              "No such interface: \"%s\"\n", interface);
 
1622
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1893
1623
      exitcode = EX_UNAVAILABLE;
1894
1624
      goto end;
1895
1625
    }
2036
1766
  
2037
1767
  ret = init_gnutls_global(pubkey, seckey);
2038
1768
  if(ret == -1){
2039
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2040
 
            "init_gnutls_global failed\n");
 
1769
    fprintf(stderr, "init_gnutls_global failed\n");
2041
1770
    exitcode = EX_UNAVAILABLE;
2042
1771
    goto end;
2043
1772
  } else {
2059
1788
  }
2060
1789
  
2061
1790
  if(not init_gpgme(pubkey, seckey, tempdir)){
2062
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2063
 
            "init_gpgme failed\n");
 
1791
    fprintf(stderr, "init_gpgme failed\n");
2064
1792
    exitcode = EX_UNAVAILABLE;
2065
1793
    goto end;
2066
1794
  } else {
2076
1804
    /* (Mainly meant for debugging) */
2077
1805
    char *address = strrchr(connect_to, ':');
2078
1806
    if(address == NULL){
2079
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2080
 
              "No colon in address\n");
 
1807
      fprintf(stderr, "No colon in address\n");
2081
1808
      exitcode = EX_USAGE;
2082
1809
      goto end;
2083
1810
    }
2091
1818
    tmpmax = strtoimax(address+1, &tmp, 10);
2092
1819
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2093
1820
       or tmpmax != (uint16_t)tmpmax){
2094
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2095
 
              "Bad port number\n");
 
1821
      fprintf(stderr, "Bad port number\n");
2096
1822
      exitcode = EX_USAGE;
2097
1823
      goto end;
2098
1824
    }
2103
1829
    
2104
1830
    port = (uint16_t)tmpmax;
2105
1831
    *address = '\0';
 
1832
    address = connect_to;
2106
1833
    /* Colon in address indicates IPv6 */
2107
1834
    int af;
2108
 
    if(strchr(connect_to, ':') != NULL){
 
1835
    if(strchr(address, ':') != NULL){
2109
1836
      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
 
        }
2116
1837
    } else {
2117
1838
      af = AF_INET;
2118
1839
    }
2119
 
    address = connect_to;
2120
1840
    
2121
1841
    if(quit_now){
2122
1842
      goto end;
2123
1843
    }
2124
 
    
 
1844
 
2125
1845
    while(not quit_now){
2126
1846
      ret = start_mandos_communication(address, port, if_index, af);
2127
1847
      if(quit_now or ret == 0){
2128
1848
        break;
2129
1849
      }
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
 
    
 
1850
      sleep((int)retry_interval or 1);
 
1851
    };
 
1852
 
2137
1853
    if (not quit_now){
2138
1854
      exitcode = EXIT_SUCCESS;
2139
1855
    }
2140
 
    
 
1856
 
2141
1857
    goto end;
2142
1858
  }
2143
1859
  
2165
1881
  
2166
1882
  /* Check if creating the Avahi server object succeeded */
2167
1883
  if(mc.server == NULL){
2168
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2169
 
            "Failed to create Avahi server: %s\n",
 
1884
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2170
1885
            avahi_strerror(error));
2171
1886
    exitcode = EX_UNAVAILABLE;
2172
1887
    goto end;
2181
1896
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2182
1897
                                   NULL, 0, browse_callback, NULL);
2183
1898
  if(sb == NULL){
2184
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2185
 
            "Failed to create service browser: %s\n",
 
1899
    fprintf(stderr, "Failed to create service browser: %s\n",
2186
1900
            avahi_strerror(avahi_server_errno(mc.server)));
2187
1901
    exitcode = EX_UNAVAILABLE;
2188
1902
    goto end;
2195
1909
  /* Run the main loop */
2196
1910
  
2197
1911
  if(debug){
2198
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2199
 
            "Starting Avahi loop search\n");
 
1912
    fprintf(stderr, "Starting Avahi loop search\n");
2200
1913
  }
2201
1914
 
2202
1915
  ret = avahi_loop_with_timeout(mc.simple_poll,
2203
1916
                                (int)(retry_interval * 1000));
2204
1917
  if(debug){
2205
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2206
 
            "avahi_loop_with_timeout exited %s\n",
 
1918
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2207
1919
            (ret == 0) ? "successfully" : "with error");
2208
1920
  }
2209
1921
  
2210
1922
 end:
2211
1923
  
2212
1924
  if(debug){
2213
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2214
 
            "%s exiting\n", argv[0]);
 
1925
    fprintf(stderr, "%s exiting\n", argv[0]);
2215
1926
  }
2216
1927
  
2217
1928
  /* Cleanup things */
2245
1956
    }
2246
1957
  }
2247
1958
  
2248
 
  /* XXX run network hooks "stop" here  */
2249
 
  
2250
1959
  /* Take down the network interface */
2251
1960
  if(take_down_interface){
2252
1961
    /* Re-raise priviliges */
2259
1968
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2260
1969
      if(ret == -1){
2261
1970
        perror_plus("ioctl SIOCGIFFLAGS");
2262
 
      } else if(network.ifr_flags & IFF_UP){
 
1971
      } else if(network.ifr_flags & IFF_UP) {
2263
1972
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2264
1973
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2265
1974
        if(ret == -1){
2283
1992
  if(tempdir_created){
2284
1993
    struct dirent **direntries = NULL;
2285
1994
    struct dirent *direntry = NULL;
2286
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2287
 
                             alphasort);
2288
 
    if (numentries > 0){
2289
 
      for(int i = 0; i < numentries; i++){
 
1995
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1996
    if (ret > 0){
 
1997
      for(int i = 0; i < ret; i++){
2290
1998
        direntry = direntries[i];
2291
1999
        char *fullname = NULL;
2292
2000
        ret = asprintf(&fullname, "%s/%s", tempdir,
2297
2005
        }
2298
2006
        ret = remove(fullname);
2299
2007
        if(ret == -1){
2300
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2301
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
2008
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2009
                  strerror(errno));
2302
2010
        }
2303
2011
        free(fullname);
2304
2012
      }
2305
2013
    }
2306
2014
 
2307
 
    /* need to clean even if 0 because man page doesn't specify */
 
2015
    /* need to be cleaned even if ret == 0 because man page doesn't
 
2016
       specify */
2308
2017
    free(direntries);
2309
 
    if (numentries == -1){
 
2018
    if (ret == -1){
2310
2019
      perror_plus("scandir");
2311
2020
    }
2312
2021
    ret = rmdir(tempdir);