/mandos/release

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

« back to all changes in this revision

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

  • Committer: Björn Påhlsson
  • Date: 2011-11-14 19:10:50 UTC
  • mto: (237.16.9 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 290.
  • Revision ID: belorn@fukt.bsnet.se-20111114191050-g11po6084bl9j5kf
replace calls to fprintf with fprintf_plus.

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_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
253
265
              gpgme_strsource(rc), gpgme_strerror(rc));
254
266
      return false;
255
267
    }
256
268
    
257
269
    rc = gpgme_op_import(mc.ctx, pgp_data);
258
270
    if(rc != GPG_ERR_NO_ERROR){
259
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
271
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
260
272
              gpgme_strsource(rc), gpgme_strerror(rc));
261
273
      return false;
262
274
    }
270
282
  }
271
283
  
272
284
  if(debug){
273
 
    fprintf(stderr, "Initializing GPGME\n");
 
285
    fprintf_plus(stderr, "Initializing GPGME\n");
274
286
  }
275
287
  
276
288
  /* Init GPGME */
277
289
  gpgme_check_version(NULL);
278
290
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
279
291
  if(rc != GPG_ERR_NO_ERROR){
280
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
292
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
281
293
            gpgme_strsource(rc), gpgme_strerror(rc));
282
294
    return false;
283
295
  }
284
296
  
285
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
297
  /* Set GPGME home directory for the OpenPGP engine only */
286
298
  rc = gpgme_get_engine_info(&engine_info);
287
299
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
300
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
289
301
            gpgme_strsource(rc), gpgme_strerror(rc));
290
302
    return false;
291
303
  }
298
310
    engine_info = engine_info->next;
299
311
  }
300
312
  if(engine_info == NULL){
301
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
313
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n", tempdir);
302
314
    return false;
303
315
  }
304
316
  
305
317
  /* Create new GPGME "context" */
306
318
  rc = gpgme_new(&(mc.ctx));
307
319
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
309
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
320
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
321
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
322
            gpgme_strerror(rc));
310
323
    return false;
311
324
  }
312
325
  
331
344
  ssize_t plaintext_length = 0;
332
345
  
333
346
  if(debug){
334
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
347
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
335
348
  }
336
349
  
337
350
  /* Create new GPGME data buffer from memory cryptotext */
338
351
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
339
352
                               0);
340
353
  if(rc != GPG_ERR_NO_ERROR){
341
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
354
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
342
355
            gpgme_strsource(rc), gpgme_strerror(rc));
343
356
    return -1;
344
357
  }
346
359
  /* Create new empty GPGME data buffer for the plaintext */
347
360
  rc = gpgme_data_new(&dh_plain);
348
361
  if(rc != GPG_ERR_NO_ERROR){
349
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
362
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
363
            "bad gpgme_data_new: %s: %s\n",
350
364
            gpgme_strsource(rc), gpgme_strerror(rc));
351
365
    gpgme_data_release(dh_crypto);
352
366
    return -1;
356
370
     data buffer */
357
371
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
358
372
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
373
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
360
374
            gpgme_strsource(rc), gpgme_strerror(rc));
361
375
    plaintext_length = -1;
362
376
    if(debug){
363
377
      gpgme_decrypt_result_t result;
364
378
      result = gpgme_op_decrypt_result(mc.ctx);
365
379
      if(result == NULL){
366
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
380
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
367
381
      } else {
368
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
382
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
369
383
                result->unsupported_algorithm);
370
 
        fprintf(stderr, "Wrong key usage: %u\n",
 
384
        fprintf_plus(stderr, "Wrong key usage: %u\n",
371
385
                result->wrong_key_usage);
372
386
        if(result->file_name != NULL){
373
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
387
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
374
388
        }
375
389
        gpgme_recipient_t recipient;
376
390
        recipient = result->recipients;
377
391
        while(recipient != NULL){
378
 
          fprintf(stderr, "Public key algorithm: %s\n",
 
392
          fprintf_plus(stderr, "Public key algorithm: %s\n",
379
393
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
380
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
381
 
          fprintf(stderr, "Secret key available: %s\n",
 
394
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
395
          fprintf_plus(stderr, "Secret key available: %s\n",
382
396
                  recipient->status == GPG_ERR_NO_SECKEY
383
397
                  ? "No" : "Yes");
384
398
          recipient = recipient->next;
389
403
  }
390
404
  
391
405
  if(debug){
392
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
406
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
393
407
  }
394
408
  
395
409
  /* Seek back to the beginning of the GPGME plaintext data buffer */
402
416
  *plaintext = NULL;
403
417
  while(true){
404
418
    plaintext_capacity = incbuffer(plaintext,
405
 
                                      (size_t)plaintext_length,
406
 
                                      plaintext_capacity);
 
419
                                   (size_t)plaintext_length,
 
420
                                   plaintext_capacity);
407
421
    if(plaintext_capacity == 0){
408
 
        perror_plus("incbuffer");
409
 
        plaintext_length = -1;
410
 
        goto decrypt_end;
 
422
      perror_plus("incbuffer");
 
423
      plaintext_length = -1;
 
424
      goto decrypt_end;
411
425
    }
412
426
    
413
427
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
426
440
  }
427
441
  
428
442
  if(debug){
429
 
    fprintf(stderr, "Decrypted password is: ");
 
443
    fprintf_plus(stderr, "Decrypted password is: ");
430
444
    for(ssize_t i = 0; i < plaintext_length; i++){
431
445
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
432
446
    }
454
468
/* GnuTLS log function callback */
455
469
static void debuggnutls(__attribute__((unused)) int level,
456
470
                        const char* string){
457
 
  fprintf(stderr, "GnuTLS: %s", string);
 
471
  fprintf_plus(stderr, "GnuTLS: %s", string);
458
472
}
459
473
 
460
474
static int init_gnutls_global(const char *pubkeyfilename,
462
476
  int ret;
463
477
  
464
478
  if(debug){
465
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
479
    fprintf_plus(stderr, "Initializing GnuTLS\n");
466
480
  }
467
481
  
468
482
  ret = gnutls_global_init();
469
483
  if(ret != GNUTLS_E_SUCCESS){
470
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
471
 
            safer_gnutls_strerror(ret));
 
484
    fprintf_plus(stderr, "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
472
485
    return -1;
473
486
  }
474
487
  
483
496
  /* OpenPGP credentials */
484
497
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
485
498
  if(ret != GNUTLS_E_SUCCESS){
486
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
487
 
            safer_gnutls_strerror(ret));
 
499
    fprintf_plus(stderr, "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
488
500
    gnutls_global_deinit();
489
501
    return -1;
490
502
  }
491
503
  
492
504
  if(debug){
493
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
505
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
494
506
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
495
507
            seckeyfilename);
496
508
  }
499
511
    (mc.cred, pubkeyfilename, seckeyfilename,
500
512
     GNUTLS_OPENPGP_FMT_BASE64);
501
513
  if(ret != GNUTLS_E_SUCCESS){
502
 
    fprintf(stderr,
503
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
504
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
505
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
506
 
            safer_gnutls_strerror(ret));
 
514
    fprintf_plus(stderr,
 
515
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
516
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
517
    fprintf_plus(stderr, "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
507
518
    goto globalfail;
508
519
  }
509
520
  
510
521
  /* GnuTLS server initialization */
511
522
  ret = gnutls_dh_params_init(&mc.dh_params);
512
523
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
524
    fprintf_plus(stderr, "Error in GnuTLS DH parameter initialization:"
514
525
            " %s\n", safer_gnutls_strerror(ret));
515
526
    goto globalfail;
516
527
  }
517
528
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
518
529
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
530
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
520
531
            safer_gnutls_strerror(ret));
521
532
    goto globalfail;
522
533
  }
543
554
    }
544
555
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
545
556
  if(ret != GNUTLS_E_SUCCESS){
546
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
557
    fprintf_plus(stderr, "Error in GnuTLS session initialization: %s\n",
547
558
            safer_gnutls_strerror(ret));
548
559
  }
549
560
  
557
568
      }
558
569
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
559
570
    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));
 
571
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
572
      fprintf_plus(stderr, "GnuTLS error: %s\n", safer_gnutls_strerror(ret));
563
573
      gnutls_deinit(*session);
564
574
      return -1;
565
575
    }
574
584
    }
575
585
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
576
586
  if(ret != GNUTLS_E_SUCCESS){
577
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
587
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
578
588
            safer_gnutls_strerror(ret));
579
589
    gnutls_deinit(*session);
580
590
    return -1;
626
636
    pf = PF_INET;
627
637
    break;
628
638
  default:
629
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
639
    fprintf_plus(stderr, "Bad address family: %d\n", af);
630
640
    errno = EINVAL;
631
641
    return -1;
632
642
  }
637
647
  }
638
648
  
639
649
  if(debug){
640
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
650
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %" PRIu16
641
651
            "\n", ip, port);
642
652
  }
643
653
  
670
680
  }
671
681
  if(ret == 0){
672
682
    int e = errno;
673
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
683
    fprintf_plus(stderr, "Bad address: %s\n", ip);
674
684
    errno = e;
675
685
    goto mandos_end;
676
686
  }
681
691
    
682
692
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
683
693
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
684
 
                              -Wunreachable-code*/
 
694
                                -Wunreachable-code*/
685
695
      if(if_index == AVAHI_IF_UNSPEC){
686
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
696
        fprintf_plus(stderr, "An IPv6 link-local address is incomplete"
687
697
                " without a network interface\n");
688
698
        errno = EINVAL;
689
699
        goto mandos_end;
708
718
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
719
        perror_plus("if_indextoname");
710
720
      } else {
711
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
721
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
712
722
                ip, interface, port);
713
723
      }
714
724
    } else {
715
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
716
 
              port);
 
725
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n", ip, port);
717
726
    }
718
727
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
719
728
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
729
738
      perror_plus("inet_ntop");
730
739
    } else {
731
740
      if(strcmp(addrstr, ip) != 0){
732
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
741
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
733
742
      }
734
743
    }
735
744
  }
763
772
  while(true){
764
773
    size_t out_size = strlen(out);
765
774
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
 
                                   out_size - written));
 
775
                                        out_size - written));
767
776
    if(ret == -1){
768
777
      int e = errno;
769
778
      perror_plus("write");
789
798
  }
790
799
  
791
800
  if(debug){
792
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
801
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
793
802
  }
794
803
  
795
804
  if(quit_now){
815
824
  
816
825
  if(ret != GNUTLS_E_SUCCESS){
817
826
    if(debug){
818
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
827
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
819
828
      gnutls_perror(ret);
820
829
    }
821
830
    errno = EPROTO;
825
834
  /* Read OpenPGP packet that contains the wanted password */
826
835
  
827
836
  if(debug){
828
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
829
 
            ip);
 
837
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from %s\n", ip);
830
838
  }
831
839
  
832
840
  while(true){
837
845
    }
838
846
    
839
847
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
 
                                   buffer_capacity);
 
848
                                buffer_capacity);
841
849
    if(buffer_capacity == 0){
842
850
      int e = errno;
843
851
      perror_plus("incbuffer");
870
878
          }
871
879
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
880
        if(ret < 0){
873
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
881
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed ***\n");
874
882
          gnutls_perror(ret);
875
883
          errno = EPROTO;
876
884
          goto mandos_end;
877
885
        }
878
886
        break;
879
887
      default:
880
 
        fprintf(stderr, "Unknown error while reading data from"
 
888
        fprintf_plus(stderr, "Unknown error while reading data from"
881
889
                " encrypted session with Mandos server\n");
882
890
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
891
        errno = EIO;
889
897
  }
890
898
  
891
899
  if(debug){
892
 
    fprintf(stderr, "Closing TLS session\n");
 
900
    fprintf_plus(stderr, "Closing TLS session\n");
893
901
  }
894
902
  
895
903
  if(quit_now){
907
915
  
908
916
  if(buffer_length > 0){
909
917
    ssize_t decrypted_buffer_size;
910
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
911
 
                                               buffer_length,
 
918
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
912
919
                                               &decrypted_buffer);
913
920
    if(decrypted_buffer_size >= 0){
914
921
      
925
932
        if(ret == 0 and ferror(stdout)){
926
933
          int e = errno;
927
934
          if(debug){
928
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
935
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
929
936
                    strerror(errno));
930
937
          }
931
938
          errno = e;
989
996
  switch(event){
990
997
  default:
991
998
  case AVAHI_RESOLVER_FAILURE:
992
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
999
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
993
1000
            " of type '%s' in domain '%s': %s\n", name, type, domain,
994
1001
            avahi_strerror(avahi_server_errno(mc.server)));
995
1002
    break;
999
1006
      char ip[AVAHI_ADDRESS_STR_MAX];
1000
1007
      avahi_address_snprint(ip, sizeof(ip), address);
1001
1008
      if(debug){
1002
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1009
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1003
1010
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1004
1011
                ip, (intmax_t)interface, port);
1005
1012
      }
1039
1046
  default:
1040
1047
  case AVAHI_BROWSER_FAILURE:
1041
1048
    
1042
 
    fprintf(stderr, "(Avahi browser) %s\n",
 
1049
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1043
1050
            avahi_strerror(avahi_server_errno(mc.server)));
1044
1051
    avahi_simple_poll_quit(mc.simple_poll);
1045
1052
    return;
1053
1060
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1054
1061
                                    name, type, domain, protocol, 0,
1055
1062
                                    resolve_callback, NULL) == NULL)
1056
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1063
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1057
1064
              name, avahi_strerror(avahi_server_errno(mc.server)));
1058
1065
    break;
1059
1066
    
1063
1070
  case AVAHI_BROWSER_ALL_FOR_NOW:
1064
1071
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1065
1072
    if(debug){
1066
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1073
      fprintf_plus(stderr, "No Mandos server found, still searching...\n");
1067
1074
    }
1068
1075
    break;
1069
1076
  }
1084
1091
  errno = old_errno;
1085
1092
}
1086
1093
 
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){
 
1094
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1095
  int ret;
 
1096
  
 
1097
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1098
  if(s < 0){
 
1099
    perror_plus("socket");
 
1100
    return false;
 
1101
  }
 
1102
  strcpy(ifr->ifr_name, ifname);
 
1103
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1104
  if(ret == -1){
1143
1105
    if(debug){
1144
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1145
 
              flagstring, if_entry->d_name);
 
1106
      perror_plus("ioctl SIOCGIFFLAGS");
1146
1107
    }
1147
 
    free(flagstring);
1148
 
    return 0;
 
1108
    return false;
1149
1109
  }
1150
 
  free(flagstring);
1151
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1110
  return true;
 
1111
}
 
1112
 
 
1113
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1114
  
1152
1115
  /* Reject the loopback device */
1153
 
  if(flags & IFF_LOOPBACK){
 
1116
  if(ifr->ifr_flags & IFF_LOOPBACK){
1154
1117
    if(debug){
1155
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1156
 
              if_entry->d_name);
 
1118
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n", ifname);
1157
1119
    }
1158
 
    return 0;
 
1120
    return false;
1159
1121
  }
1160
1122
  /* Accept point-to-point devices only if connect_to is specified */
1161
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1123
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1162
1124
    if(debug){
1163
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1164
 
              if_entry->d_name);
 
1125
      fprintf_plus(stderr, "Accepting point-to-point interface \"%s\"\n", ifname);
1165
1126
    }
1166
 
    return 1;
 
1127
    return true;
1167
1128
  }
1168
1129
  /* Otherwise, reject non-broadcast-capable devices */
1169
 
  if(not (flags & IFF_BROADCAST)){
 
1130
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1170
1131
    if(debug){
1171
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1172
 
              if_entry->d_name);
 
1132
      fprintf_plus(stderr, "Rejecting non-broadcast interface \"%s\"\n", ifname);
1173
1133
    }
1174
 
    return 0;
 
1134
    return false;
1175
1135
  }
1176
1136
  /* Reject non-ARP interfaces (including dummy interfaces) */
1177
 
  if(flags & IFF_NOARP){
 
1137
  if(ifr->ifr_flags & IFF_NOARP){
1178
1138
    if(debug){
1179
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1180
 
              if_entry->d_name);
 
1139
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
1181
1140
    }
1182
 
    return 0;
 
1141
    return false;
1183
1142
  }
 
1143
  
1184
1144
  /* Accept this device */
1185
1145
  if(debug){
1186
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1187
 
            if_entry->d_name);
 
1146
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1147
  }
 
1148
  return true;
 
1149
}
 
1150
 
 
1151
/* 
 
1152
 * This function determines if a directory entry in /sys/class/net
 
1153
 * corresponds to an acceptable network device.
 
1154
 * (This function is passed to scandir(3) as a filter function.)
 
1155
 */
 
1156
int good_interface(const struct dirent *if_entry){
 
1157
  if(if_entry->d_name[0] == '.'){
 
1158
    return 0;
 
1159
  }
 
1160
  
 
1161
  struct ifreq ifr;
 
1162
  if(not get_flags(if_entry->d_name, &ifr)){
 
1163
    if(debug){
 
1164
      fprintf_plus(stderr, "Failed to get flags for interface \"%s\"\n",
 
1165
              if_entry->d_name);
 
1166
    }
 
1167
    return 0;
 
1168
  }
 
1169
  
 
1170
  if(not good_flags(if_entry->d_name, &ifr)){
 
1171
    return 0;
 
1172
  }
 
1173
  return 1;
 
1174
}
 
1175
 
 
1176
/* 
 
1177
 * This function determines if a directory entry in /sys/class/net
 
1178
 * corresponds to an acceptable network device which is up.
 
1179
 * (This function is passed to scandir(3) as a filter function.)
 
1180
 */
 
1181
int up_interface(const struct dirent *if_entry){
 
1182
  if(if_entry->d_name[0] == '.'){
 
1183
    return 0;
 
1184
  }
 
1185
  
 
1186
  struct ifreq ifr;
 
1187
  if(not get_flags(if_entry->d_name, &ifr)){
 
1188
    if(debug){
 
1189
      fprintf_plus(stderr, "Failed to get flags for interface \"%s\"\n",
 
1190
              if_entry->d_name);
 
1191
    }
 
1192
    return 0;
 
1193
  }
 
1194
  
 
1195
  /* Reject down interfaces */
 
1196
  if(not (ifr.ifr_flags & IFF_UP)){
 
1197
    if(debug){
 
1198
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1199
              if_entry->d_name);
 
1200
    }
 
1201
    return 0;
 
1202
  }
 
1203
  
 
1204
  /* Reject non-running interfaces */
 
1205
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1206
    if(debug){
 
1207
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1208
              if_entry->d_name);
 
1209
    }
 
1210
    return 0;
 
1211
  }
 
1212
  
 
1213
  if(not good_flags(if_entry->d_name, &ifr)){
 
1214
    return 0;
1188
1215
  }
1189
1216
  return 1;
1190
1217
}
1200
1227
  return 1;
1201
1228
}
1202
1229
 
 
1230
/* Is this directory entry a runnable program? */
 
1231
int runnable_hook(const struct dirent *direntry){
 
1232
  int ret;
 
1233
  size_t sret;
 
1234
  struct stat st;
 
1235
  
 
1236
  if((direntry->d_name)[0] == '\0'){
 
1237
    /* Empty name? */
 
1238
    return 0;
 
1239
  }
 
1240
  
 
1241
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1242
                "abcdefghijklmnopqrstuvwxyz"
 
1243
                "0123456789"
 
1244
                "_-");
 
1245
  if((direntry->d_name)[sret] != '\0'){
 
1246
    /* Contains non-allowed characters */
 
1247
    if(debug){
 
1248
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1249
              direntry->d_name);
 
1250
    }
 
1251
    return 0;
 
1252
  }
 
1253
  
 
1254
  char *fullname = NULL;
 
1255
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1256
  if(ret < 0){
 
1257
    perror_plus("asprintf");
 
1258
    return 0;
 
1259
  }
 
1260
  
 
1261
  ret = stat(fullname, &st);
 
1262
  if(ret == -1){
 
1263
    if(debug){
 
1264
      perror_plus("Could not stat hook");
 
1265
    }
 
1266
    return 0;
 
1267
  }
 
1268
  if(not (S_ISREG(st.st_mode))){
 
1269
    /* Not a regular file */
 
1270
    if(debug){
 
1271
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1272
              direntry->d_name);
 
1273
    }
 
1274
    return 0;
 
1275
  }
 
1276
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1277
    /* Not executable */
 
1278
    if(debug){
 
1279
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1280
              direntry->d_name);
 
1281
    }
 
1282
    return 0;
 
1283
  }
 
1284
  return 1;
 
1285
}
 
1286
 
1203
1287
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1204
1288
  int ret;
1205
1289
  struct timespec now;
1206
1290
  struct timespec waited_time;
1207
1291
  intmax_t block_time;
1208
 
 
 
1292
  
1209
1293
  while(true){
1210
1294
    if(mc.current_server == NULL){
1211
1295
      if (debug){
1212
 
        fprintf(stderr,
1213
 
                "Wait until first server is found. No timeout!\n");
 
1296
        fprintf_plus(stderr, "Wait until first server is found. No timeout!\n");
1214
1297
      }
1215
1298
      ret = avahi_simple_poll_iterate(s, -1);
1216
1299
    } else {
1217
1300
      if (debug){
1218
 
        fprintf(stderr, "Check current_server if we should run it,"
 
1301
        fprintf_plus(stderr, "Check current_server if we should run it,"
1219
1302
                " or wait\n");
1220
1303
      }
1221
1304
      /* the current time */
1236
1319
      block_time = ((retry_interval
1237
1320
                     - ((intmax_t)waited_time.tv_sec * 1000))
1238
1321
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1239
 
 
 
1322
      
1240
1323
      if (debug){
1241
 
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1324
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1242
1325
      }
1243
 
 
 
1326
      
1244
1327
      if(block_time <= 0){
1245
1328
        ret = start_mandos_communication(mc.current_server->ip,
1246
1329
                                         mc.current_server->port,
1264
1347
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1265
1348
    }
1266
1349
    if(ret != 0){
1267
 
      if (ret > 0 or errno != EINTR) {
 
1350
      if (ret > 0 or errno != EINTR){
1268
1351
        return (ret != 1) ? ret : 0;
1269
1352
      }
1270
1353
    }
1358
1441
        .arg = "SECONDS",
1359
1442
        .doc = "Retry interval used when denied by the mandos server",
1360
1443
        .group = 2 },
 
1444
      { .name = "network-hook-dir", .key = 133,
 
1445
        .arg = "DIR",
 
1446
        .doc = "Directory where network hooks are located",
 
1447
        .group = 2 },
1361
1448
      /*
1362
1449
       * These reproduce what we would get without ARGP_NO_HELP
1363
1450
       */
1411
1498
        errno = 0;
1412
1499
        retry_interval = strtod(arg, &tmp);
1413
1500
        if(errno != 0 or tmp == arg or *tmp != '\0'
1414
 
           or (retry_interval * 1000) > INT_MAX){
 
1501
           or (retry_interval * 1000) > INT_MAX
 
1502
           or retry_interval < 0){
1415
1503
          argp_error(state, "Bad retry interval");
1416
1504
        }
1417
1505
        break;
 
1506
      case 133:                 /* --network-hook-dir */
 
1507
        hookdir = arg;
 
1508
        break;
1418
1509
        /*
1419
1510
         * These reproduce what we would get without ARGP_NO_HELP
1420
1511
         */
1426
1517
        argp_state_help(state, state->out_stream,
1427
1518
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1428
1519
      case 'V':                 /* --version */
1429
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1520
        fprintf_plus(state->out_stream, "Mandos plugin mandos-client: ");
 
1521
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1430
1522
        exit(argp_err_exit_status);
1431
1523
        break;
1432
1524
      default:
1468
1560
      perror_plus("seteuid");
1469
1561
    }
1470
1562
    
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");
 
1563
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1564
      int seckey_fd = open(seckey, O_RDONLY);
 
1565
      if(seckey_fd == -1){
 
1566
        perror_plus("open");
1478
1567
      } else {
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");
 
1568
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1569
        if(ret == -1){
 
1570
          perror_plus("fstat");
 
1571
        } else {
 
1572
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1573
            ret = fchown(seckey_fd, uid, gid);
 
1574
            if(ret == -1){
 
1575
              perror_plus("fchown");
 
1576
            }
1483
1577
          }
1484
1578
        }
 
1579
        TEMP_FAILURE_RETRY(close(seckey_fd));
1485
1580
      }
1486
 
      TEMP_FAILURE_RETRY(close(seckey_fd));
1487
1581
    }
1488
1582
    
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");
 
1583
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1584
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1585
      if(pubkey_fd == -1){
 
1586
        perror_plus("open");
1496
1587
      } else {
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");
 
1588
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1589
        if(ret == -1){
 
1590
          perror_plus("fstat");
 
1591
        } else {
 
1592
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1593
            ret = fchown(pubkey_fd, uid, gid);
 
1594
            if(ret == -1){
 
1595
              perror_plus("fchown");
 
1596
            }
1501
1597
          }
1502
1598
        }
 
1599
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1503
1600
      }
1504
 
      TEMP_FAILURE_RETRY(close(pubkey_fd));
1505
1601
    }
1506
1602
    
1507
1603
    /* Lower privileges */
1512
1608
    }
1513
1609
  }
1514
1610
  
 
1611
  /* Find network hooks and run them */
 
1612
  {
 
1613
    struct dirent **direntries;
 
1614
    struct dirent *direntry;
 
1615
    int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1616
                           alphasort);
 
1617
    if(numhooks == -1){
 
1618
      perror_plus("scandir");
 
1619
    } else {
 
1620
      int devnull = open("/dev/null", O_RDONLY);
 
1621
      for(int i = 0; i < numhooks; i++){
 
1622
        direntry = direntries[0];
 
1623
        char *fullname = NULL;
 
1624
        ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1625
        if(ret < 0){
 
1626
          perror_plus("asprintf");
 
1627
          continue;
 
1628
        }
 
1629
        pid_t hook_pid = fork();
 
1630
        if(hook_pid == 0){
 
1631
          /* Child */
 
1632
          dup2(devnull, STDIN_FILENO);
 
1633
          close(devnull);
 
1634
          dup2(STDERR_FILENO, STDOUT_FILENO);
 
1635
          ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1636
          if(ret == -1){
 
1637
            perror_plus("setenv");
 
1638
            exit(1);
 
1639
          }
 
1640
          ret = setenv("DEVICE", interface, 1);
 
1641
          if(ret == -1){
 
1642
            perror_plus("setenv");
 
1643
            exit(1);
 
1644
          }
 
1645
          ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1646
          if(ret == -1){
 
1647
            perror_plus("setenv");
 
1648
            exit(1);
 
1649
          }
 
1650
          ret = setenv("MODE", "start", 1);
 
1651
          if(ret == -1){
 
1652
            perror_plus("setenv");
 
1653
            exit(1);
 
1654
          }
 
1655
          char *delaystring;
 
1656
          ret = asprintf(&delaystring, "%f", delay);
 
1657
          if(ret == -1){
 
1658
            perror_plus("asprintf");
 
1659
            exit(1);
 
1660
          }
 
1661
          ret = setenv("DELAY", delaystring, 1);
 
1662
          if(ret == -1){
 
1663
            free(delaystring);
 
1664
            perror_plus("setenv");
 
1665
            exit(1);
 
1666
          }
 
1667
          free(delaystring);
 
1668
          ret = execl(fullname, direntry->d_name, "start", NULL);
 
1669
          perror_plus("execl");
 
1670
        } else {
 
1671
          int status;
 
1672
          if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1673
            perror_plus("waitpid");
 
1674
            free(fullname);
 
1675
            continue;
 
1676
          }
 
1677
          if(WIFEXITED(status)){
 
1678
            if(WEXITSTATUS(status) != 0){
 
1679
              fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1680
                      " with status %d\n", direntry->d_name,
 
1681
                      WEXITSTATUS(status));
 
1682
              free(fullname);
 
1683
              continue;
 
1684
            }
 
1685
          } else if(WIFSIGNALED(status)){
 
1686
            fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1687
                    " signal %d\n", direntry->d_name,
 
1688
                    WTERMSIG(status));
 
1689
            free(fullname);
 
1690
            continue;
 
1691
          } else {
 
1692
            fprintf_plus(stderr, "Warning: network hook \"%s\" crashed\n",
 
1693
                    direntry->d_name);
 
1694
            free(fullname);
 
1695
            continue;
 
1696
          }
 
1697
        }
 
1698
        free(fullname);
 
1699
        if(quit_now){
 
1700
          goto end;
 
1701
        }
 
1702
      }
 
1703
      close(devnull);
 
1704
    }
 
1705
  }
 
1706
  
1515
1707
  if(not debug){
1516
1708
    avahi_set_log_function(empty_log);
1517
1709
  }
1518
 
 
 
1710
  
1519
1711
  if(interface[0] == '\0'){
1520
1712
    struct dirent **direntries;
1521
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1713
    /* First look for interfaces that are up */
 
1714
    ret = scandir(sys_class_net, &direntries, up_interface,
1522
1715
                  alphasort);
 
1716
    if(ret == 0){
 
1717
      /* No up interfaces, look for any good interfaces */
 
1718
      free(direntries);
 
1719
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1720
                    alphasort);
 
1721
    }
1523
1722
    if(ret >= 1){
1524
 
      /* Pick the first good interface */
 
1723
      /* Pick the first interface returned */
1525
1724
      interface = strdup(direntries[0]->d_name);
1526
1725
      if(debug){
1527
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1726
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1528
1727
      }
1529
1728
      if(interface == NULL){
1530
1729
        perror_plus("malloc");
1535
1734
      free(direntries);
1536
1735
    } else {
1537
1736
      free(direntries);
1538
 
      fprintf(stderr, "Could not find a network interface\n");
 
1737
      fprintf_plus(stderr, "Could not find a network interface\n");
1539
1738
      exitcode = EXIT_FAILURE;
1540
1739
      goto end;
1541
1740
    }
1547
1746
  srand((unsigned int) time(NULL));
1548
1747
  mc.simple_poll = avahi_simple_poll_new();
1549
1748
  if(mc.simple_poll == NULL){
1550
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1749
    fprintf_plus(stderr, "Avahi: Failed to create simple poll object.\n");
1551
1750
    exitcode = EX_UNAVAILABLE;
1552
1751
    goto end;
1553
1752
  }
1619
1818
  if(strcmp(interface, "none") != 0){
1620
1819
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1621
1820
    if(if_index == 0){
1622
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1821
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1623
1822
      exitcode = EX_UNAVAILABLE;
1624
1823
      goto end;
1625
1824
    }
1766
1965
  
1767
1966
  ret = init_gnutls_global(pubkey, seckey);
1768
1967
  if(ret == -1){
1769
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
1968
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1770
1969
    exitcode = EX_UNAVAILABLE;
1771
1970
    goto end;
1772
1971
  } else {
1788
1987
  }
1789
1988
  
1790
1989
  if(not init_gpgme(pubkey, seckey, tempdir)){
1791
 
    fprintf(stderr, "init_gpgme failed\n");
 
1990
    fprintf_plus(stderr, "init_gpgme failed\n");
1792
1991
    exitcode = EX_UNAVAILABLE;
1793
1992
    goto end;
1794
1993
  } else {
1804
2003
    /* (Mainly meant for debugging) */
1805
2004
    char *address = strrchr(connect_to, ':');
1806
2005
    if(address == NULL){
1807
 
      fprintf(stderr, "No colon in address\n");
 
2006
      fprintf_plus(stderr, "No colon in address\n");
1808
2007
      exitcode = EX_USAGE;
1809
2008
      goto end;
1810
2009
    }
1818
2017
    tmpmax = strtoimax(address+1, &tmp, 10);
1819
2018
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1820
2019
       or tmpmax != (uint16_t)tmpmax){
1821
 
      fprintf(stderr, "Bad port number\n");
 
2020
      fprintf_plus(stderr, "Bad port number\n");
1822
2021
      exitcode = EX_USAGE;
1823
2022
      goto end;
1824
2023
    }
1829
2028
    
1830
2029
    port = (uint16_t)tmpmax;
1831
2030
    *address = '\0';
1832
 
    address = connect_to;
1833
2031
    /* Colon in address indicates IPv6 */
1834
2032
    int af;
1835
 
    if(strchr(address, ':') != NULL){
 
2033
    if(strchr(connect_to, ':') != NULL){
1836
2034
      af = AF_INET6;
 
2035
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2036
      if(connect_to[0] == '[' and address[-1] == ']')
 
2037
        {
 
2038
          connect_to++;
 
2039
          address[-1] = '\0';
 
2040
        }
1837
2041
    } else {
1838
2042
      af = AF_INET;
1839
2043
    }
 
2044
    address = connect_to;
1840
2045
    
1841
2046
    if(quit_now){
1842
2047
      goto end;
1843
2048
    }
1844
 
 
 
2049
    
1845
2050
    while(not quit_now){
1846
2051
      ret = start_mandos_communication(address, port, if_index, af);
1847
2052
      if(quit_now or ret == 0){
1848
2053
        break;
1849
2054
      }
1850
 
      sleep((int)retry_interval or 1);
1851
 
    };
1852
 
 
 
2055
      if(debug){
 
2056
        fprintf_plus(stderr, "Retrying in %d seconds\n", (int)retry_interval);
 
2057
      }
 
2058
      sleep((int)retry_interval);
 
2059
    }
 
2060
    
1853
2061
    if (not quit_now){
1854
2062
      exitcode = EXIT_SUCCESS;
1855
2063
    }
1856
 
 
 
2064
    
1857
2065
    goto end;
1858
2066
  }
1859
2067
  
1881
2089
  
1882
2090
  /* Check if creating the Avahi server object succeeded */
1883
2091
  if(mc.server == NULL){
1884
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
2092
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
1885
2093
            avahi_strerror(error));
1886
2094
    exitcode = EX_UNAVAILABLE;
1887
2095
    goto end;
1896
2104
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1897
2105
                                   NULL, 0, browse_callback, NULL);
1898
2106
  if(sb == NULL){
1899
 
    fprintf(stderr, "Failed to create service browser: %s\n",
 
2107
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
1900
2108
            avahi_strerror(avahi_server_errno(mc.server)));
1901
2109
    exitcode = EX_UNAVAILABLE;
1902
2110
    goto end;
1909
2117
  /* Run the main loop */
1910
2118
  
1911
2119
  if(debug){
1912
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2120
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1913
2121
  }
1914
2122
 
1915
2123
  ret = avahi_loop_with_timeout(mc.simple_poll,
1916
2124
                                (int)(retry_interval * 1000));
1917
2125
  if(debug){
1918
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
2126
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
1919
2127
            (ret == 0) ? "successfully" : "with error");
1920
2128
  }
1921
2129
  
1922
2130
 end:
1923
2131
  
1924
2132
  if(debug){
1925
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2133
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1926
2134
  }
1927
2135
  
1928
2136
  /* Cleanup things */
1956
2164
    }
1957
2165
  }
1958
2166
  
 
2167
  /* XXX run network hooks "stop" here  */
 
2168
  
1959
2169
  /* Take down the network interface */
1960
2170
  if(take_down_interface){
1961
2171
    /* Re-raise priviliges */
1968
2178
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1969
2179
      if(ret == -1){
1970
2180
        perror_plus("ioctl SIOCGIFFLAGS");
1971
 
      } else if(network.ifr_flags & IFF_UP) {
 
2181
      } else if(network.ifr_flags & IFF_UP){
1972
2182
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1973
2183
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1974
2184
        if(ret == -1){
1992
2202
  if(tempdir_created){
1993
2203
    struct dirent **direntries = NULL;
1994
2204
    struct dirent *direntry = NULL;
1995
 
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
1996
 
    if (ret > 0){
1997
 
      for(int i = 0; i < ret; i++){
 
2205
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2206
                             alphasort);
 
2207
    if (numentries > 0){
 
2208
      for(int i = 0; i < numentries; i++){
1998
2209
        direntry = direntries[i];
1999
2210
        char *fullname = NULL;
2000
2211
        ret = asprintf(&fullname, "%s/%s", tempdir,
2005
2216
        }
2006
2217
        ret = remove(fullname);
2007
2218
        if(ret == -1){
2008
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2009
 
                  strerror(errno));
 
2219
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname, strerror(errno));
2010
2220
        }
2011
2221
        free(fullname);
2012
2222
      }
2013
2223
    }
2014
2224
 
2015
 
    /* need to be cleaned even if ret == 0 because man page doesn't
2016
 
       specify */
 
2225
    /* need to clean even if 0 because man page doesn't specify */
2017
2226
    free(direntries);
2018
 
    if (ret == -1){
 
2227
    if (numentries == -1){
2019
2228
      perror_plus("scandir");
2020
2229
    }
2021
2230
    ret = rmdir(tempdir);