/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

* plugins.d/mandos-client.c: Merge unified printing system.

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: ",
 
182
                             program_invocation_short_name));
 
183
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
184
}
 
185
 
173
186
/*
174
187
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
188
 * bytes. "buffer_capacity" is how much is currently allocated,
176
189
 * "buffer_length" is how much is already used.
177
190
 */
178
191
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
192
                 size_t buffer_capacity){
180
193
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
194
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
195
    if(buffer == NULL){
187
200
  return buffer_capacity;
188
201
}
189
202
 
190
 
int add_server(const char *ip, uint16_t port,
191
 
                 AvahiIfIndex if_index,
192
 
                 int af){
 
203
/* Add server to set of servers to retry periodically */
 
204
int add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
 
205
               int af){
193
206
  int ret;
194
207
  server *new_server = malloc(sizeof(server));
195
208
  if(new_server == NULL){
197
210
    return -1;
198
211
  }
199
212
  *new_server = (server){ .ip = strdup(ip),
200
 
                         .port = port,
201
 
                         .if_index = if_index,
202
 
                         .af = af };
 
213
                          .port = port,
 
214
                          .if_index = if_index,
 
215
                          .af = af };
203
216
  if(new_server->ip == NULL){
204
217
    perror_plus("strdup");
205
218
    return -1;
206
219
  }
207
 
  /* unique case of first server */
 
220
  /* Special case of first server */
208
221
  if (mc.current_server == NULL){
209
222
    new_server->next = new_server;
210
223
    new_server->prev = new_server;
211
224
    mc.current_server = new_server;
212
 
  /* Placing the new server last in the list */
 
225
  /* Place the new server last in the list */
213
226
  } else {
214
227
    new_server->next = mc.current_server;
215
228
    new_server->prev = mc.current_server->prev;
227
240
/* 
228
241
 * Initialize GPGME.
229
242
 */
230
 
static bool init_gpgme(const char *seckey,
231
 
                       const char *pubkey, const char *tempdir){
 
243
static bool init_gpgme(const char *seckey, const char *pubkey,
 
244
                       const char *tempdir){
232
245
  gpgme_error_t rc;
233
246
  gpgme_engine_info_t engine_info;
234
247
  
249
262
    
250
263
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
251
264
    if(rc != GPG_ERR_NO_ERROR){
252
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
253
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
265
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
266
                   gpgme_strsource(rc), gpgme_strerror(rc));
254
267
      return false;
255
268
    }
256
269
    
257
270
    rc = gpgme_op_import(mc.ctx, pgp_data);
258
271
    if(rc != GPG_ERR_NO_ERROR){
259
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
260
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
272
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
273
                   gpgme_strsource(rc), gpgme_strerror(rc));
261
274
      return false;
262
275
    }
263
276
    
270
283
  }
271
284
  
272
285
  if(debug){
273
 
    fprintf(stderr, "Initializing GPGME\n");
 
286
    fprintf_plus(stderr, "Initializing GPGME\n");
274
287
  }
275
288
  
276
289
  /* Init GPGME */
277
290
  gpgme_check_version(NULL);
278
291
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
279
292
  if(rc != GPG_ERR_NO_ERROR){
280
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
281
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
293
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
294
                 gpgme_strsource(rc), gpgme_strerror(rc));
282
295
    return false;
283
296
  }
284
297
  
285
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
298
  /* Set GPGME home directory for the OpenPGP engine only */
286
299
  rc = gpgme_get_engine_info(&engine_info);
287
300
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
289
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
301
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
302
                 gpgme_strsource(rc), gpgme_strerror(rc));
290
303
    return false;
291
304
  }
292
305
  while(engine_info != NULL){
298
311
    engine_info = engine_info->next;
299
312
  }
300
313
  if(engine_info == NULL){
301
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
314
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
315
                 tempdir);
302
316
    return false;
303
317
  }
304
318
  
305
319
  /* Create new GPGME "context" */
306
320
  rc = gpgme_new(&(mc.ctx));
307
321
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
309
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
322
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
323
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
324
                 gpgme_strerror(rc));
310
325
    return false;
311
326
  }
312
327
  
331
346
  ssize_t plaintext_length = 0;
332
347
  
333
348
  if(debug){
334
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
349
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
335
350
  }
336
351
  
337
352
  /* Create new GPGME data buffer from memory cryptotext */
338
353
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
339
354
                               0);
340
355
  if(rc != GPG_ERR_NO_ERROR){
341
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
342
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
356
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
357
                 gpgme_strsource(rc), gpgme_strerror(rc));
343
358
    return -1;
344
359
  }
345
360
  
346
361
  /* Create new empty GPGME data buffer for the plaintext */
347
362
  rc = gpgme_data_new(&dh_plain);
348
363
  if(rc != GPG_ERR_NO_ERROR){
349
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
350
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
364
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
365
                 "bad gpgme_data_new: %s: %s\n",
 
366
                 gpgme_strsource(rc), gpgme_strerror(rc));
351
367
    gpgme_data_release(dh_crypto);
352
368
    return -1;
353
369
  }
356
372
     data buffer */
357
373
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
358
374
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
360
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
375
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
376
                 gpgme_strsource(rc), gpgme_strerror(rc));
361
377
    plaintext_length = -1;
362
378
    if(debug){
363
379
      gpgme_decrypt_result_t result;
364
380
      result = gpgme_op_decrypt_result(mc.ctx);
365
381
      if(result == NULL){
366
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
382
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
367
383
      } else {
368
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
369
 
                result->unsupported_algorithm);
370
 
        fprintf(stderr, "Wrong key usage: %u\n",
371
 
                result->wrong_key_usage);
 
384
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
385
                     result->unsupported_algorithm);
 
386
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
387
                     result->wrong_key_usage);
372
388
        if(result->file_name != NULL){
373
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
389
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
374
390
        }
375
391
        gpgme_recipient_t recipient;
376
392
        recipient = result->recipients;
377
393
        while(recipient != NULL){
378
 
          fprintf(stderr, "Public key algorithm: %s\n",
379
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
380
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
381
 
          fprintf(stderr, "Secret key available: %s\n",
382
 
                  recipient->status == GPG_ERR_NO_SECKEY
383
 
                  ? "No" : "Yes");
 
394
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
395
                       gpgme_pubkey_algo_name
 
396
                       (recipient->pubkey_algo));
 
397
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
398
          fprintf_plus(stderr, "Secret key available: %s\n",
 
399
                       recipient->status == GPG_ERR_NO_SECKEY
 
400
                       ? "No" : "Yes");
384
401
          recipient = recipient->next;
385
402
        }
386
403
      }
389
406
  }
390
407
  
391
408
  if(debug){
392
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
409
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
393
410
  }
394
411
  
395
412
  /* Seek back to the beginning of the GPGME plaintext data buffer */
402
419
  *plaintext = NULL;
403
420
  while(true){
404
421
    plaintext_capacity = incbuffer(plaintext,
405
 
                                      (size_t)plaintext_length,
406
 
                                      plaintext_capacity);
 
422
                                   (size_t)plaintext_length,
 
423
                                   plaintext_capacity);
407
424
    if(plaintext_capacity == 0){
408
 
        perror_plus("incbuffer");
409
 
        plaintext_length = -1;
410
 
        goto decrypt_end;
 
425
      perror_plus("incbuffer");
 
426
      plaintext_length = -1;
 
427
      goto decrypt_end;
411
428
    }
412
429
    
413
430
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
426
443
  }
427
444
  
428
445
  if(debug){
429
 
    fprintf(stderr, "Decrypted password is: ");
 
446
    fprintf_plus(stderr, "Decrypted password is: ");
430
447
    for(ssize_t i = 0; i < plaintext_length; i++){
431
448
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
432
449
    }
454
471
/* GnuTLS log function callback */
455
472
static void debuggnutls(__attribute__((unused)) int level,
456
473
                        const char* string){
457
 
  fprintf(stderr, "GnuTLS: %s", string);
 
474
  fprintf_plus(stderr, "GnuTLS: %s", string);
458
475
}
459
476
 
460
477
static int init_gnutls_global(const char *pubkeyfilename,
462
479
  int ret;
463
480
  
464
481
  if(debug){
465
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
482
    fprintf_plus(stderr, "Initializing GnuTLS\n");
466
483
  }
467
484
  
468
485
  ret = gnutls_global_init();
469
486
  if(ret != GNUTLS_E_SUCCESS){
470
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
471
 
            safer_gnutls_strerror(ret));
 
487
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
488
                 safer_gnutls_strerror(ret));
472
489
    return -1;
473
490
  }
474
491
  
483
500
  /* OpenPGP credentials */
484
501
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
485
502
  if(ret != GNUTLS_E_SUCCESS){
486
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
487
 
            safer_gnutls_strerror(ret));
 
503
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
504
                 safer_gnutls_strerror(ret));
488
505
    gnutls_global_deinit();
489
506
    return -1;
490
507
  }
491
508
  
492
509
  if(debug){
493
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
494
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
495
 
            seckeyfilename);
 
510
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
511
                 " secret key %s as GnuTLS credentials\n",
 
512
                 pubkeyfilename,
 
513
                 seckeyfilename);
496
514
  }
497
515
  
498
516
  ret = gnutls_certificate_set_openpgp_key_file
499
517
    (mc.cred, pubkeyfilename, seckeyfilename,
500
518
     GNUTLS_OPENPGP_FMT_BASE64);
501
519
  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));
 
520
    fprintf_plus(stderr,
 
521
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
522
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
523
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
524
                 safer_gnutls_strerror(ret));
507
525
    goto globalfail;
508
526
  }
509
527
  
510
528
  /* GnuTLS server initialization */
511
529
  ret = gnutls_dh_params_init(&mc.dh_params);
512
530
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
514
 
            " %s\n", safer_gnutls_strerror(ret));
 
531
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
532
                 " initialization: %s\n",
 
533
                 safer_gnutls_strerror(ret));
515
534
    goto globalfail;
516
535
  }
517
536
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
518
537
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
520
 
            safer_gnutls_strerror(ret));
 
538
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
539
                 safer_gnutls_strerror(ret));
521
540
    goto globalfail;
522
541
  }
523
542
  
543
562
    }
544
563
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
545
564
  if(ret != GNUTLS_E_SUCCESS){
546
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
547
 
            safer_gnutls_strerror(ret));
 
565
    fprintf_plus(stderr,
 
566
                 "Error in GnuTLS session initialization: %s\n",
 
567
                 safer_gnutls_strerror(ret));
548
568
  }
549
569
  
550
570
  {
557
577
      }
558
578
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
559
579
    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));
 
580
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
581
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
582
                   safer_gnutls_strerror(ret));
563
583
      gnutls_deinit(*session);
564
584
      return -1;
565
585
    }
574
594
    }
575
595
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
576
596
  if(ret != GNUTLS_E_SUCCESS){
577
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
578
 
            safer_gnutls_strerror(ret));
 
597
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
598
                 safer_gnutls_strerror(ret));
579
599
    gnutls_deinit(*session);
580
600
    return -1;
581
601
  }
626
646
    pf = PF_INET;
627
647
    break;
628
648
  default:
629
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
649
    fprintf_plus(stderr, "Bad address family: %d\n", af);
630
650
    errno = EINVAL;
631
651
    return -1;
632
652
  }
637
657
  }
638
658
  
639
659
  if(debug){
640
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
641
 
            "\n", ip, port);
 
660
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
661
                 PRIu16 "\n", ip, port);
642
662
  }
643
663
  
644
664
  tcp_sd = socket(pf, SOCK_STREAM, 0);
670
690
  }
671
691
  if(ret == 0){
672
692
    int e = errno;
673
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
693
    fprintf_plus(stderr, "Bad address: %s\n", ip);
674
694
    errno = e;
675
695
    goto mandos_end;
676
696
  }
681
701
    
682
702
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
683
703
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
684
 
                              -Wunreachable-code*/
 
704
                                -Wunreachable-code*/
685
705
      if(if_index == AVAHI_IF_UNSPEC){
686
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
687
 
                " without a network interface\n");
 
706
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
707
                     " incomplete without a network interface\n");
688
708
        errno = EINVAL;
689
709
        goto mandos_end;
690
710
      }
708
728
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
729
        perror_plus("if_indextoname");
710
730
      } else {
711
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
712
 
                ip, interface, port);
 
731
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
732
                     "\n", ip, interface, port);
713
733
      }
714
734
    } else {
715
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
716
 
              port);
 
735
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
736
                   ip, port);
717
737
    }
718
738
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
719
739
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
729
749
      perror_plus("inet_ntop");
730
750
    } else {
731
751
      if(strcmp(addrstr, ip) != 0){
732
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
752
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
733
753
      }
734
754
    }
735
755
  }
763
783
  while(true){
764
784
    size_t out_size = strlen(out);
765
785
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
 
                                   out_size - written));
 
786
                                        out_size - written));
767
787
    if(ret == -1){
768
788
      int e = errno;
769
789
      perror_plus("write");
789
809
  }
790
810
  
791
811
  if(debug){
792
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
812
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
793
813
  }
794
814
  
795
815
  if(quit_now){
815
835
  
816
836
  if(ret != GNUTLS_E_SUCCESS){
817
837
    if(debug){
818
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
838
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
819
839
      gnutls_perror(ret);
820
840
    }
821
841
    errno = EPROTO;
825
845
  /* Read OpenPGP packet that contains the wanted password */
826
846
  
827
847
  if(debug){
828
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
829
 
            ip);
 
848
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
849
                 " %s\n", ip);
830
850
  }
831
851
  
832
852
  while(true){
837
857
    }
838
858
    
839
859
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
 
                                   buffer_capacity);
 
860
                                buffer_capacity);
841
861
    if(buffer_capacity == 0){
842
862
      int e = errno;
843
863
      perror_plus("incbuffer");
870
890
          }
871
891
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
892
        if(ret < 0){
873
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
893
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
894
                       "***\n");
874
895
          gnutls_perror(ret);
875
896
          errno = EPROTO;
876
897
          goto mandos_end;
877
898
        }
878
899
        break;
879
900
      default:
880
 
        fprintf(stderr, "Unknown error while reading data from"
881
 
                " encrypted session with Mandos server\n");
 
901
        fprintf_plus(stderr, "Unknown error while reading data from"
 
902
                     " encrypted session with Mandos server\n");
882
903
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
904
        errno = EIO;
884
905
        goto mandos_end;
889
910
  }
890
911
  
891
912
  if(debug){
892
 
    fprintf(stderr, "Closing TLS session\n");
 
913
    fprintf_plus(stderr, "Closing TLS session\n");
893
914
  }
894
915
  
895
916
  if(quit_now){
907
928
  
908
929
  if(buffer_length > 0){
909
930
    ssize_t decrypted_buffer_size;
910
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
911
 
                                               buffer_length,
 
931
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
912
932
                                               &decrypted_buffer);
913
933
    if(decrypted_buffer_size >= 0){
914
934
      
925
945
        if(ret == 0 and ferror(stdout)){
926
946
          int e = errno;
927
947
          if(debug){
928
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
929
 
                    strerror(errno));
 
948
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
949
                         strerror(errno));
930
950
          }
931
951
          errno = e;
932
952
          goto mandos_end;
989
1009
  switch(event){
990
1010
  default:
991
1011
  case AVAHI_RESOLVER_FAILURE:
992
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
993
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
994
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1012
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1013
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1014
                 domain,
 
1015
                 avahi_strerror(avahi_server_errno(mc.server)));
995
1016
    break;
996
1017
    
997
1018
  case AVAHI_RESOLVER_FOUND:
999
1020
      char ip[AVAHI_ADDRESS_STR_MAX];
1000
1021
      avahi_address_snprint(ip, sizeof(ip), address);
1001
1022
      if(debug){
1002
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1003
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1004
 
                ip, (intmax_t)interface, port);
 
1023
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1024
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1025
                     host_name, ip, (intmax_t)interface, port);
1005
1026
      }
1006
1027
      int ret = start_mandos_communication(ip, port, interface,
1007
1028
                                           avahi_proto_to_af(proto));
1039
1060
  default:
1040
1061
  case AVAHI_BROWSER_FAILURE:
1041
1062
    
1042
 
    fprintf(stderr, "(Avahi browser) %s\n",
1043
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1063
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1064
                 avahi_strerror(avahi_server_errno(mc.server)));
1044
1065
    avahi_simple_poll_quit(mc.simple_poll);
1045
1066
    return;
1046
1067
    
1053
1074
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1054
1075
                                    name, type, domain, protocol, 0,
1055
1076
                                    resolve_callback, NULL) == NULL)
1056
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1057
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1077
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1078
                   " %s\n", name,
 
1079
                   avahi_strerror(avahi_server_errno(mc.server)));
1058
1080
    break;
1059
1081
    
1060
1082
  case AVAHI_BROWSER_REMOVE:
1063
1085
  case AVAHI_BROWSER_ALL_FOR_NOW:
1064
1086
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1065
1087
    if(debug){
1066
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1088
      fprintf_plus(stderr, "No Mandos server found, still"
 
1089
                   " searching...\n");
1067
1090
    }
1068
1091
    break;
1069
1092
  }
1084
1107
  errno = old_errno;
1085
1108
}
1086
1109
 
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){
 
1110
bool get_flags(const char *ifname, struct ifreq *ifr){
 
1111
  int ret;
 
1112
  
 
1113
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1114
  if(s < 0){
 
1115
    perror_plus("socket");
 
1116
    return false;
 
1117
  }
 
1118
  strcpy(ifr->ifr_name, ifname);
 
1119
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
 
1120
  if(ret == -1){
1143
1121
    if(debug){
1144
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1145
 
              flagstring, if_entry->d_name);
 
1122
      perror_plus("ioctl SIOCGIFFLAGS");
1146
1123
    }
1147
 
    free(flagstring);
1148
 
    return 0;
 
1124
    return false;
1149
1125
  }
1150
 
  free(flagstring);
1151
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1126
  return true;
 
1127
}
 
1128
 
 
1129
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1130
  
1152
1131
  /* Reject the loopback device */
1153
 
  if(flags & IFF_LOOPBACK){
 
1132
  if(ifr->ifr_flags & IFF_LOOPBACK){
1154
1133
    if(debug){
1155
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1156
 
              if_entry->d_name);
 
1134
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1135
                   ifname);
1157
1136
    }
1158
 
    return 0;
 
1137
    return false;
1159
1138
  }
1160
1139
  /* Accept point-to-point devices only if connect_to is specified */
1161
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1140
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1162
1141
    if(debug){
1163
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1164
 
              if_entry->d_name);
 
1142
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1143
                   " \"%s\"\n", ifname);
1165
1144
    }
1166
 
    return 1;
 
1145
    return true;
1167
1146
  }
1168
1147
  /* Otherwise, reject non-broadcast-capable devices */
1169
 
  if(not (flags & IFF_BROADCAST)){
 
1148
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1170
1149
    if(debug){
1171
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1172
 
              if_entry->d_name);
 
1150
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1151
                   " \"%s\"\n", ifname);
1173
1152
    }
1174
 
    return 0;
 
1153
    return false;
1175
1154
  }
1176
1155
  /* Reject non-ARP interfaces (including dummy interfaces) */
1177
 
  if(flags & IFF_NOARP){
 
1156
  if(ifr->ifr_flags & IFF_NOARP){
1178
1157
    if(debug){
1179
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1180
 
              if_entry->d_name);
 
1158
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1159
                   ifname);
1181
1160
    }
1182
 
    return 0;
 
1161
    return false;
1183
1162
  }
 
1163
  
1184
1164
  /* Accept this device */
1185
1165
  if(debug){
1186
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1187
 
            if_entry->d_name);
 
1166
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
 
1167
  }
 
1168
  return true;
 
1169
}
 
1170
 
 
1171
/* 
 
1172
 * This function determines if a directory entry in /sys/class/net
 
1173
 * corresponds to an acceptable network device.
 
1174
 * (This function is passed to scandir(3) as a filter function.)
 
1175
 */
 
1176
int good_interface(const struct dirent *if_entry){
 
1177
  if(if_entry->d_name[0] == '.'){
 
1178
    return 0;
 
1179
  }
 
1180
  
 
1181
  struct ifreq ifr;
 
1182
  if(not get_flags(if_entry->d_name, &ifr)){
 
1183
    if(debug){
 
1184
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1185
                   "\"%s\"\n", if_entry->d_name);
 
1186
    }
 
1187
    return 0;
 
1188
  }
 
1189
  
 
1190
  if(not good_flags(if_entry->d_name, &ifr)){
 
1191
    return 0;
 
1192
  }
 
1193
  return 1;
 
1194
}
 
1195
 
 
1196
/* 
 
1197
 * This function determines if a directory entry in /sys/class/net
 
1198
 * corresponds to an acceptable network device which is up.
 
1199
 * (This function is passed to scandir(3) as a filter function.)
 
1200
 */
 
1201
int up_interface(const struct dirent *if_entry){
 
1202
  if(if_entry->d_name[0] == '.'){
 
1203
    return 0;
 
1204
  }
 
1205
  
 
1206
  struct ifreq ifr;
 
1207
  if(not get_flags(if_entry->d_name, &ifr)){
 
1208
    if(debug){
 
1209
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1210
                   "\"%s\"\n", if_entry->d_name);
 
1211
    }
 
1212
    return 0;
 
1213
  }
 
1214
  
 
1215
  /* Reject down interfaces */
 
1216
  if(not (ifr.ifr_flags & IFF_UP)){
 
1217
    if(debug){
 
1218
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
 
1219
                   if_entry->d_name);
 
1220
    }
 
1221
    return 0;
 
1222
  }
 
1223
  
 
1224
  /* Reject non-running interfaces */
 
1225
  if(not (ifr.ifr_flags & IFF_RUNNING)){
 
1226
    if(debug){
 
1227
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
 
1228
                   if_entry->d_name);
 
1229
    }
 
1230
    return 0;
 
1231
  }
 
1232
  
 
1233
  if(not good_flags(if_entry->d_name, &ifr)){
 
1234
    return 0;
1188
1235
  }
1189
1236
  return 1;
1190
1237
}
1200
1247
  return 1;
1201
1248
}
1202
1249
 
 
1250
/* Is this directory entry a runnable program? */
 
1251
int runnable_hook(const struct dirent *direntry){
 
1252
  int ret;
 
1253
  size_t sret;
 
1254
  struct stat st;
 
1255
  
 
1256
  if((direntry->d_name)[0] == '\0'){
 
1257
    /* Empty name? */
 
1258
    return 0;
 
1259
  }
 
1260
  
 
1261
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1262
                "abcdefghijklmnopqrstuvwxyz"
 
1263
                "0123456789"
 
1264
                "_-");
 
1265
  if((direntry->d_name)[sret] != '\0'){
 
1266
    /* Contains non-allowed characters */
 
1267
    if(debug){
 
1268
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1269
                   direntry->d_name);
 
1270
    }
 
1271
    return 0;
 
1272
  }
 
1273
  
 
1274
  char *fullname = NULL;
 
1275
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1276
  if(ret < 0){
 
1277
    perror_plus("asprintf");
 
1278
    return 0;
 
1279
  }
 
1280
  
 
1281
  ret = stat(fullname, &st);
 
1282
  if(ret == -1){
 
1283
    if(debug){
 
1284
      perror_plus("Could not stat hook");
 
1285
    }
 
1286
    return 0;
 
1287
  }
 
1288
  if(not (S_ISREG(st.st_mode))){
 
1289
    /* Not a regular file */
 
1290
    if(debug){
 
1291
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1292
                   direntry->d_name);
 
1293
    }
 
1294
    return 0;
 
1295
  }
 
1296
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
 
1297
    /* Not executable */
 
1298
    if(debug){
 
1299
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1300
                   direntry->d_name);
 
1301
    }
 
1302
    return 0;
 
1303
  }
 
1304
  return 1;
 
1305
}
 
1306
 
1203
1307
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1204
1308
  int ret;
1205
1309
  struct timespec now;
1206
1310
  struct timespec waited_time;
1207
1311
  intmax_t block_time;
1208
 
 
 
1312
  
1209
1313
  while(true){
1210
1314
    if(mc.current_server == NULL){
1211
1315
      if (debug){
1212
 
        fprintf(stderr,
1213
 
                "Wait until first server is found. No timeout!\n");
 
1316
        fprintf_plus(stderr, "Wait until first server is found."
 
1317
                     " No timeout!\n");
1214
1318
      }
1215
1319
      ret = avahi_simple_poll_iterate(s, -1);
1216
1320
    } else {
1217
1321
      if (debug){
1218
 
        fprintf(stderr, "Check current_server if we should run it,"
1219
 
                " or wait\n");
 
1322
        fprintf_plus(stderr, "Check current_server if we should run"
 
1323
                     " it, or wait\n");
1220
1324
      }
1221
1325
      /* the current time */
1222
1326
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1236
1340
      block_time = ((retry_interval
1237
1341
                     - ((intmax_t)waited_time.tv_sec * 1000))
1238
1342
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1239
 
 
 
1343
      
1240
1344
      if (debug){
1241
 
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1345
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1346
                     block_time);
1242
1347
      }
1243
 
 
 
1348
      
1244
1349
      if(block_time <= 0){
1245
1350
        ret = start_mandos_communication(mc.current_server->ip,
1246
1351
                                         mc.current_server->port,
1264
1369
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1265
1370
    }
1266
1371
    if(ret != 0){
1267
 
      if (ret > 0 or errno != EINTR) {
 
1372
      if (ret > 0 or errno != EINTR){
1268
1373
        return (ret != 1) ? ret : 0;
1269
1374
      }
1270
1375
    }
1271
1376
  }
1272
1377
}
1273
1378
 
 
1379
bool run_network_hooks(const char *mode, const char *interface,
 
1380
                       const float delay){
 
1381
  struct dirent **direntries;
 
1382
  struct dirent *direntry;
 
1383
  int ret;
 
1384
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1385
                         alphasort);
 
1386
  if(numhooks == -1){
 
1387
    perror_plus("scandir");
 
1388
  } else {
 
1389
    int devnull = open("/dev/null", O_RDONLY);
 
1390
    for(int i = 0; i < numhooks; i++){
 
1391
      direntry = direntries[0];
 
1392
      char *fullname = NULL;
 
1393
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
 
1394
      if(ret < 0){
 
1395
        perror_plus("asprintf");
 
1396
        continue;
 
1397
      }
 
1398
      pid_t hook_pid = fork();
 
1399
      if(hook_pid == 0){
 
1400
        /* Child */
 
1401
        dup2(devnull, STDIN_FILENO);
 
1402
        close(devnull);
 
1403
        dup2(STDERR_FILENO, STDOUT_FILENO);
 
1404
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1405
        if(ret == -1){
 
1406
          perror_plus("setenv");
 
1407
          return false;
 
1408
        }
 
1409
        ret = setenv("DEVICE", interface, 1);
 
1410
        if(ret == -1){
 
1411
          perror_plus("setenv");
 
1412
          return false;
 
1413
        }
 
1414
        ret = setenv("VERBOSE", debug ? "1" : "0", 1);
 
1415
        if(ret == -1){
 
1416
          perror_plus("setenv");
 
1417
          return false;
 
1418
        }
 
1419
        ret = setenv("MODE", mode, 1);
 
1420
        if(ret == -1){
 
1421
          perror_plus("setenv");
 
1422
          return false;
 
1423
        }
 
1424
        char *delaystring;
 
1425
        ret = asprintf(&delaystring, "%f", delay);
 
1426
        if(ret == -1){
 
1427
          perror_plus("asprintf");
 
1428
          return false;
 
1429
        }
 
1430
        ret = setenv("DELAY", delaystring, 1);
 
1431
        if(ret == -1){
 
1432
          free(delaystring);
 
1433
          perror_plus("setenv");
 
1434
          return false;
 
1435
        }
 
1436
        free(delaystring);
 
1437
        ret = execl(fullname, direntry->d_name, mode, NULL);
 
1438
        perror_plus("execl");
 
1439
      } else {
 
1440
        int status;
 
1441
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1442
          perror_plus("waitpid");
 
1443
          free(fullname);
 
1444
          continue;
 
1445
        }
 
1446
        if(WIFEXITED(status)){
 
1447
          if(WEXITSTATUS(status) != 0){
 
1448
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1449
                         " with status %d\n", direntry->d_name,
 
1450
                         WEXITSTATUS(status));
 
1451
            free(fullname);
 
1452
            continue;
 
1453
          }
 
1454
        } else if(WIFSIGNALED(status)){
 
1455
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1456
                       " signal %d\n", direntry->d_name,
 
1457
                       WTERMSIG(status));
 
1458
          free(fullname);
 
1459
          continue;
 
1460
        } else {
 
1461
          fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1462
                       " crashed\n", direntry->d_name);
 
1463
          free(fullname);
 
1464
          continue;
 
1465
        }
 
1466
      }
 
1467
      free(fullname);
 
1468
      if(quit_now){
 
1469
        break;
 
1470
      }
 
1471
    }
 
1472
    close(devnull);
 
1473
  }
 
1474
  return true;
 
1475
}
 
1476
 
1274
1477
int main(int argc, char *argv[]){
1275
1478
  AvahiSServiceBrowser *sb = NULL;
1276
1479
  int error;
1358
1561
        .arg = "SECONDS",
1359
1562
        .doc = "Retry interval used when denied by the mandos server",
1360
1563
        .group = 2 },
 
1564
      { .name = "network-hook-dir", .key = 133,
 
1565
        .arg = "DIR",
 
1566
        .doc = "Directory where network hooks are located",
 
1567
        .group = 2 },
1361
1568
      /*
1362
1569
       * These reproduce what we would get without ARGP_NO_HELP
1363
1570
       */
1411
1618
        errno = 0;
1412
1619
        retry_interval = strtod(arg, &tmp);
1413
1620
        if(errno != 0 or tmp == arg or *tmp != '\0'
1414
 
           or (retry_interval * 1000) > INT_MAX){
 
1621
           or (retry_interval * 1000) > INT_MAX
 
1622
           or retry_interval < 0){
1415
1623
          argp_error(state, "Bad retry interval");
1416
1624
        }
1417
1625
        break;
 
1626
      case 133:                 /* --network-hook-dir */
 
1627
        hookdir = arg;
 
1628
        break;
1418
1629
        /*
1419
1630
         * These reproduce what we would get without ARGP_NO_HELP
1420
1631
         */
1426
1637
        argp_state_help(state, state->out_stream,
1427
1638
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1428
1639
      case 'V':                 /* --version */
1429
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1640
        fprintf_plus(state->out_stream,
 
1641
                     "Mandos plugin mandos-client: ");
 
1642
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1430
1643
        exit(argp_err_exit_status);
1431
1644
        break;
1432
1645
      default:
1455
1668
      goto end;
1456
1669
    }
1457
1670
  }
 
1671
    
 
1672
  {
 
1673
    /* Work around Debian bug #633582:
 
1674
       <http://bugs.debian.org/633582> */
 
1675
    struct stat st;
 
1676
    
 
1677
    /* Re-raise priviliges */
 
1678
    errno = 0;
 
1679
    ret = seteuid(0);
 
1680
    if(ret == -1){
 
1681
      perror_plus("seteuid");
 
1682
    }
 
1683
    
 
1684
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1685
      int seckey_fd = open(seckey, O_RDONLY);
 
1686
      if(seckey_fd == -1){
 
1687
        perror_plus("open");
 
1688
      } else {
 
1689
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1690
        if(ret == -1){
 
1691
          perror_plus("fstat");
 
1692
        } else {
 
1693
          if(S_ISREG(st.st_mode)
 
1694
             and st.st_uid == 0 and st.st_gid == 0){
 
1695
            ret = fchown(seckey_fd, uid, gid);
 
1696
            if(ret == -1){
 
1697
              perror_plus("fchown");
 
1698
            }
 
1699
          }
 
1700
        }
 
1701
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1702
      }
 
1703
    }
 
1704
    
 
1705
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1706
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1707
      if(pubkey_fd == -1){
 
1708
        perror_plus("open");
 
1709
      } else {
 
1710
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1711
        if(ret == -1){
 
1712
          perror_plus("fstat");
 
1713
        } else {
 
1714
          if(S_ISREG(st.st_mode)
 
1715
             and st.st_uid == 0 and st.st_gid == 0){
 
1716
            ret = fchown(pubkey_fd, uid, gid);
 
1717
            if(ret == -1){
 
1718
              perror_plus("fchown");
 
1719
            }
 
1720
          }
 
1721
        }
 
1722
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1723
      }
 
1724
    }
 
1725
    
 
1726
    /* Lower privileges */
 
1727
    errno = 0;
 
1728
    ret = seteuid(uid);
 
1729
    if(ret == -1){
 
1730
      perror_plus("seteuid");
 
1731
    }
 
1732
  }
 
1733
  
 
1734
  /* Run network hooks */
 
1735
  {
 
1736
    /* Re-raise priviliges */
 
1737
    errno = 0;
 
1738
    ret = seteuid(0);
 
1739
    if(ret == -1){
 
1740
      perror_plus("seteuid");
 
1741
    }
 
1742
    if(not run_network_hooks("start", interface, delay)){
 
1743
      goto end;
 
1744
    }
 
1745
    /* Lower privileges */
 
1746
    errno = 0;
 
1747
    ret = seteuid(uid);
 
1748
    if(ret == -1){
 
1749
      perror_plus("seteuid");
 
1750
    }
 
1751
  }
1458
1752
  
1459
1753
  if(not debug){
1460
1754
    avahi_set_log_function(empty_log);
1461
1755
  }
1462
 
 
 
1756
  
1463
1757
  if(interface[0] == '\0'){
1464
1758
    struct dirent **direntries;
1465
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1759
    /* First look for interfaces that are up */
 
1760
    ret = scandir(sys_class_net, &direntries, up_interface,
1466
1761
                  alphasort);
 
1762
    if(ret == 0){
 
1763
      /* No up interfaces, look for any good interfaces */
 
1764
      free(direntries);
 
1765
      ret = scandir(sys_class_net, &direntries, good_interface,
 
1766
                    alphasort);
 
1767
    }
1467
1768
    if(ret >= 1){
1468
 
      /* Pick the first good interface */
 
1769
      /* Pick the first interface returned */
1469
1770
      interface = strdup(direntries[0]->d_name);
1470
1771
      if(debug){
1471
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1772
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1472
1773
      }
1473
1774
      if(interface == NULL){
1474
1775
        perror_plus("malloc");
1479
1780
      free(direntries);
1480
1781
    } else {
1481
1782
      free(direntries);
1482
 
      fprintf(stderr, "Could not find a network interface\n");
 
1783
      fprintf_plus(stderr, "Could not find a network interface\n");
1483
1784
      exitcode = EXIT_FAILURE;
1484
1785
      goto end;
1485
1786
    }
1491
1792
  srand((unsigned int) time(NULL));
1492
1793
  mc.simple_poll = avahi_simple_poll_new();
1493
1794
  if(mc.simple_poll == NULL){
1494
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1795
    fprintf_plus(stderr,
 
1796
                 "Avahi: Failed to create simple poll object.\n");
1495
1797
    exitcode = EX_UNAVAILABLE;
1496
1798
    goto end;
1497
1799
  }
1563
1865
  if(strcmp(interface, "none") != 0){
1564
1866
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1565
1867
    if(if_index == 0){
1566
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1868
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1567
1869
      exitcode = EX_UNAVAILABLE;
1568
1870
      goto end;
1569
1871
    }
1689
1991
#endif  /* __linux__ */
1690
1992
    /* Lower privileges */
1691
1993
    errno = 0;
1692
 
    if(take_down_interface){
1693
 
      /* Lower privileges */
1694
 
      ret = seteuid(uid);
1695
 
      if(ret == -1){
1696
 
        perror_plus("seteuid");
1697
 
      }
1698
 
    } else {
1699
 
      /* Lower privileges permanently */
1700
 
      ret = setuid(uid);
1701
 
      if(ret == -1){
1702
 
        perror_plus("setuid");
1703
 
      }
 
1994
    /* Lower privileges */
 
1995
    ret = seteuid(uid);
 
1996
    if(ret == -1){
 
1997
      perror_plus("seteuid");
1704
1998
    }
1705
1999
  }
1706
2000
  
1710
2004
  
1711
2005
  ret = init_gnutls_global(pubkey, seckey);
1712
2006
  if(ret == -1){
1713
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2007
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1714
2008
    exitcode = EX_UNAVAILABLE;
1715
2009
    goto end;
1716
2010
  } else {
1732
2026
  }
1733
2027
  
1734
2028
  if(not init_gpgme(pubkey, seckey, tempdir)){
1735
 
    fprintf(stderr, "init_gpgme failed\n");
 
2029
    fprintf_plus(stderr, "init_gpgme failed\n");
1736
2030
    exitcode = EX_UNAVAILABLE;
1737
2031
    goto end;
1738
2032
  } else {
1748
2042
    /* (Mainly meant for debugging) */
1749
2043
    char *address = strrchr(connect_to, ':');
1750
2044
    if(address == NULL){
1751
 
      fprintf(stderr, "No colon in address\n");
 
2045
      fprintf_plus(stderr, "No colon in address\n");
1752
2046
      exitcode = EX_USAGE;
1753
2047
      goto end;
1754
2048
    }
1762
2056
    tmpmax = strtoimax(address+1, &tmp, 10);
1763
2057
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1764
2058
       or tmpmax != (uint16_t)tmpmax){
1765
 
      fprintf(stderr, "Bad port number\n");
 
2059
      fprintf_plus(stderr, "Bad port number\n");
1766
2060
      exitcode = EX_USAGE;
1767
2061
      goto end;
1768
2062
    }
1773
2067
    
1774
2068
    port = (uint16_t)tmpmax;
1775
2069
    *address = '\0';
1776
 
    address = connect_to;
1777
2070
    /* Colon in address indicates IPv6 */
1778
2071
    int af;
1779
 
    if(strchr(address, ':') != NULL){
 
2072
    if(strchr(connect_to, ':') != NULL){
1780
2073
      af = AF_INET6;
 
2074
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2075
      if(connect_to[0] == '[' and address[-1] == ']')
 
2076
        {
 
2077
          connect_to++;
 
2078
          address[-1] = '\0';
 
2079
        }
1781
2080
    } else {
1782
2081
      af = AF_INET;
1783
2082
    }
 
2083
    address = connect_to;
1784
2084
    
1785
2085
    if(quit_now){
1786
2086
      goto end;
1787
2087
    }
1788
 
 
 
2088
    
1789
2089
    while(not quit_now){
1790
2090
      ret = start_mandos_communication(address, port, if_index, af);
1791
2091
      if(quit_now or ret == 0){
1792
2092
        break;
1793
2093
      }
1794
 
      sleep((int)retry_interval or 1);
1795
 
    };
1796
 
 
 
2094
      if(debug){
 
2095
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2096
                     (int)retry_interval);
 
2097
      }
 
2098
      sleep((int)retry_interval);
 
2099
    }
 
2100
    
1797
2101
    if (not quit_now){
1798
2102
      exitcode = EXIT_SUCCESS;
1799
2103
    }
1800
 
 
 
2104
    
1801
2105
    goto end;
1802
2106
  }
1803
2107
  
1825
2129
  
1826
2130
  /* Check if creating the Avahi server object succeeded */
1827
2131
  if(mc.server == NULL){
1828
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1829
 
            avahi_strerror(error));
 
2132
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2133
                 avahi_strerror(error));
1830
2134
    exitcode = EX_UNAVAILABLE;
1831
2135
    goto end;
1832
2136
  }
1840
2144
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1841
2145
                                   NULL, 0, browse_callback, NULL);
1842
2146
  if(sb == NULL){
1843
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1844
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2147
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2148
                 avahi_strerror(avahi_server_errno(mc.server)));
1845
2149
    exitcode = EX_UNAVAILABLE;
1846
2150
    goto end;
1847
2151
  }
1853
2157
  /* Run the main loop */
1854
2158
  
1855
2159
  if(debug){
1856
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2160
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1857
2161
  }
1858
2162
 
1859
2163
  ret = avahi_loop_with_timeout(mc.simple_poll,
1860
2164
                                (int)(retry_interval * 1000));
1861
2165
  if(debug){
1862
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1863
 
            (ret == 0) ? "successfully" : "with error");
 
2166
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2167
                 (ret == 0) ? "successfully" : "with error");
1864
2168
  }
1865
2169
  
1866
2170
 end:
1867
2171
  
1868
2172
  if(debug){
1869
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2173
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1870
2174
  }
1871
2175
  
1872
2176
  /* Cleanup things */
1900
2204
    }
1901
2205
  }
1902
2206
  
1903
 
  /* Take down the network interface */
1904
 
  if(take_down_interface){
1905
 
    /* Re-raise priviliges */
 
2207
  /* Re-raise priviliges */
 
2208
  {
1906
2209
    errno = 0;
1907
2210
    ret = seteuid(0);
1908
2211
    if(ret == -1){
1909
2212
      perror_plus("seteuid");
1910
2213
    }
1911
 
    if(geteuid() == 0){
 
2214
    /* Run network hooks */
 
2215
    if(not run_network_hooks("stop", interface, delay)){
 
2216
      goto end;
 
2217
    }
 
2218
    
 
2219
    /* Take down the network interface */
 
2220
    if(take_down_interface and geteuid() == 0){
1912
2221
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1913
2222
      if(ret == -1){
1914
2223
        perror_plus("ioctl SIOCGIFFLAGS");
1915
 
      } else if(network.ifr_flags & IFF_UP) {
 
2224
      } else if(network.ifr_flags & IFF_UP){
1916
2225
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1917
2226
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1918
2227
        if(ret == -1){
1923
2232
      if(ret == -1){
1924
2233
        perror_plus("close");
1925
2234
      }
1926
 
      /* Lower privileges permanently */
1927
 
      errno = 0;
1928
 
      ret = setuid(uid);
1929
 
      if(ret == -1){
1930
 
        perror_plus("setuid");
1931
 
      }
1932
2235
    }
1933
2236
  }
 
2237
  /* Lower privileges permanently */
 
2238
  errno = 0;
 
2239
  ret = setuid(uid);
 
2240
  if(ret == -1){
 
2241
    perror_plus("setuid");
 
2242
  }
1934
2243
  
1935
2244
  /* Removes the GPGME temp directory and all files inside */
1936
2245
  if(tempdir_created){
1937
2246
    struct dirent **direntries = NULL;
1938
2247
    struct dirent *direntry = NULL;
1939
 
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
1940
 
    if (ret > 0){
1941
 
      for(int i = 0; i < ret; i++){
 
2248
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2249
                             alphasort);
 
2250
    if (numentries > 0){
 
2251
      for(int i = 0; i < numentries; i++){
1942
2252
        direntry = direntries[i];
1943
2253
        char *fullname = NULL;
1944
2254
        ret = asprintf(&fullname, "%s/%s", tempdir,
1949
2259
        }
1950
2260
        ret = remove(fullname);
1951
2261
        if(ret == -1){
1952
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1953
 
                  strerror(errno));
 
2262
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2263
                       strerror(errno));
1954
2264
        }
1955
2265
        free(fullname);
1956
2266
      }
1957
2267
    }
1958
2268
 
1959
 
    /* need to be cleaned even if ret == 0 because man page doesn't
1960
 
       specify */
 
2269
    /* need to clean even if 0 because man page doesn't specify */
1961
2270
    free(direntries);
1962
 
    if (ret == -1){
 
2271
    if (numentries == -1){
1963
2272
      perror_plus("scandir");
1964
2273
    }
1965
2274
    ret = rmdir(tempdir);