/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Björn Påhlsson
  • Date: 2011-10-02 19:18:24 UTC
  • mto: This revision was merged to the branch mainline in revision 505.
  • Revision ID: belorn@fukt.bsnet.se-20111002191824-eweh4pvneeg3qzia
transitional stuff actually working
documented change to D-Bus API

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
 
76
                                   setgid(), pause() */
77
77
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
78
78
#include <iso646.h>             /* not, or, and */
79
79
#include <argp.h>               /* struct argp_option, error_t, struct
85
85
                                   raise() */
86
86
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
87
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
 
#include <grp.h>                /* setgroups() */
91
88
 
92
89
#ifdef __linux__
93
90
#include <sys/klog.h>           /* klogctl() */
111
108
                                   init_gnutls_session(),
112
109
                                   GNUTLS_* */
113
110
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
111
                          /* gnutls_certificate_set_openpgp_key_file(),
 
112
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
113
 
117
114
/* GPGME */
118
115
#include <gpgme.h>              /* All GPGME types, constants and
126
123
#define PATHDIR "/conf/conf.d/mandos"
127
124
#define SECKEY "seckey.txt"
128
125
#define PUBKEY "pubkey.txt"
129
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
130
126
 
131
127
bool debug = false;
132
128
static const char mandos_protocol_version[] = "1";
133
129
const char *argp_program_version = "mandos-client " VERSION;
134
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
130
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
135
131
static const char sys_class_net[] = "/sys/class/net";
136
132
char *connect_to = NULL;
137
 
const char *hookdir = HOOKDIR;
138
133
 
139
134
/* Doubly linked list that need to be circularly linked when used */
140
135
typedef struct server{
170
165
 
171
166
/* Function to use when printing errors */
172
167
void perror_plus(const char *print_text){
173
 
  int e = errno;
174
168
  fprintf(stderr, "Mandos plugin %s: ",
175
169
          program_invocation_short_name);
176
 
  errno = e;
177
170
  perror(print_text);
178
171
}
179
172
 
180
 
__attribute__((format (gnu_printf, 2, 3)))
181
 
int fprintf_plus(FILE *stream, const char *format, ...){
182
 
  va_list ap;
183
 
  va_start (ap, format);
184
 
  
185
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
186
 
                             program_invocation_short_name));
187
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
188
 
}
189
 
 
190
173
/*
191
174
 * Make additional room in "buffer" for at least BUFFER_SIZE more
192
175
 * bytes. "buffer_capacity" is how much is currently allocated,
193
176
 * "buffer_length" is how much is already used.
194
177
 */
195
178
size_t incbuffer(char **buffer, size_t buffer_length,
196
 
                 size_t buffer_capacity){
 
179
                  size_t buffer_capacity){
197
180
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
198
181
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
199
182
    if(buffer == NULL){
205
188
}
206
189
 
207
190
/* Add server to set of servers to retry periodically */
208
 
bool add_server(const char *ip, uint16_t port, AvahiIfIndex if_index,
209
 
                int af){
 
191
int add_server(const char *ip, uint16_t port,
 
192
                 AvahiIfIndex if_index,
 
193
                 int af){
210
194
  int ret;
211
195
  server *new_server = malloc(sizeof(server));
212
196
  if(new_server == NULL){
213
197
    perror_plus("malloc");
214
 
    return false;
 
198
    return -1;
215
199
  }
216
200
  *new_server = (server){ .ip = strdup(ip),
217
 
                          .port = port,
218
 
                          .if_index = if_index,
219
 
                          .af = af };
 
201
                         .port = port,
 
202
                         .if_index = if_index,
 
203
                         .af = af };
220
204
  if(new_server->ip == NULL){
221
205
    perror_plus("strdup");
222
 
    return false;
 
206
    return -1;
223
207
  }
224
208
  /* Special case of first server */
225
209
  if (mc.current_server == NULL){
236
220
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
237
221
  if(ret == -1){
238
222
    perror_plus("clock_gettime");
239
 
    return false;
 
223
    return -1;
240
224
  }
241
 
  return true;
 
225
  return 0;
242
226
}
243
227
 
244
228
/* 
245
229
 * Initialize GPGME.
246
230
 */
247
 
static bool init_gpgme(const char *seckey, const char *pubkey,
248
 
                       const char *tempdir){
 
231
static bool init_gpgme(const char *seckey,
 
232
                       const char *pubkey, const char *tempdir){
249
233
  gpgme_error_t rc;
250
234
  gpgme_engine_info_t engine_info;
251
235
  
266
250
    
267
251
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
268
252
    if(rc != GPG_ERR_NO_ERROR){
269
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
270
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
253
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
254
              gpgme_strsource(rc), gpgme_strerror(rc));
271
255
      return false;
272
256
    }
273
257
    
274
258
    rc = gpgme_op_import(mc.ctx, pgp_data);
275
259
    if(rc != GPG_ERR_NO_ERROR){
276
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
277
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
260
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
261
              gpgme_strsource(rc), gpgme_strerror(rc));
278
262
      return false;
279
263
    }
280
264
    
287
271
  }
288
272
  
289
273
  if(debug){
290
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
274
    fprintf(stderr, "Initializing GPGME\n");
291
275
  }
292
276
  
293
277
  /* Init GPGME */
294
278
  gpgme_check_version(NULL);
295
279
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
296
280
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
298
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
281
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
282
            gpgme_strsource(rc), gpgme_strerror(rc));
299
283
    return false;
300
284
  }
301
285
  
302
286
  /* Set GPGME home directory for the OpenPGP engine only */
303
287
  rc = gpgme_get_engine_info(&engine_info);
304
288
  if(rc != GPG_ERR_NO_ERROR){
305
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
306
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
289
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
290
            gpgme_strsource(rc), gpgme_strerror(rc));
307
291
    return false;
308
292
  }
309
293
  while(engine_info != NULL){
315
299
    engine_info = engine_info->next;
316
300
  }
317
301
  if(engine_info == NULL){
318
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
319
 
                 tempdir);
 
302
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
320
303
    return false;
321
304
  }
322
305
  
323
306
  /* Create new GPGME "context" */
324
307
  rc = gpgme_new(&(mc.ctx));
325
308
  if(rc != GPG_ERR_NO_ERROR){
326
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
327
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
328
 
                 gpgme_strerror(rc));
 
309
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
310
            gpgme_strsource(rc), gpgme_strerror(rc));
329
311
    return false;
330
312
  }
331
313
  
350
332
  ssize_t plaintext_length = 0;
351
333
  
352
334
  if(debug){
353
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
335
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
354
336
  }
355
337
  
356
338
  /* Create new GPGME data buffer from memory cryptotext */
357
339
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
358
340
                               0);
359
341
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
361
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
342
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
343
            gpgme_strsource(rc), gpgme_strerror(rc));
362
344
    return -1;
363
345
  }
364
346
  
365
347
  /* Create new empty GPGME data buffer for the plaintext */
366
348
  rc = gpgme_data_new(&dh_plain);
367
349
  if(rc != GPG_ERR_NO_ERROR){
368
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
369
 
                 "bad gpgme_data_new: %s: %s\n",
370
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
350
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
351
            gpgme_strsource(rc), gpgme_strerror(rc));
371
352
    gpgme_data_release(dh_crypto);
372
353
    return -1;
373
354
  }
376
357
     data buffer */
377
358
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
378
359
  if(rc != GPG_ERR_NO_ERROR){
379
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
380
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
360
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
361
            gpgme_strsource(rc), gpgme_strerror(rc));
381
362
    plaintext_length = -1;
382
363
    if(debug){
383
364
      gpgme_decrypt_result_t result;
384
365
      result = gpgme_op_decrypt_result(mc.ctx);
385
366
      if(result == NULL){
386
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
367
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
387
368
      } else {
388
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
389
 
                     result->unsupported_algorithm);
390
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
391
 
                     result->wrong_key_usage);
 
369
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
370
                result->unsupported_algorithm);
 
371
        fprintf(stderr, "Wrong key usage: %u\n",
 
372
                result->wrong_key_usage);
392
373
        if(result->file_name != NULL){
393
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
374
          fprintf(stderr, "File name: %s\n", result->file_name);
394
375
        }
395
376
        gpgme_recipient_t recipient;
396
377
        recipient = result->recipients;
397
378
        while(recipient != NULL){
398
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
399
 
                       gpgme_pubkey_algo_name
400
 
                       (recipient->pubkey_algo));
401
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
402
 
          fprintf_plus(stderr, "Secret key available: %s\n",
403
 
                       recipient->status == GPG_ERR_NO_SECKEY
404
 
                       ? "No" : "Yes");
 
379
          fprintf(stderr, "Public key algorithm: %s\n",
 
380
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
381
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
382
          fprintf(stderr, "Secret key available: %s\n",
 
383
                  recipient->status == GPG_ERR_NO_SECKEY
 
384
                  ? "No" : "Yes");
405
385
          recipient = recipient->next;
406
386
        }
407
387
      }
410
390
  }
411
391
  
412
392
  if(debug){
413
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
393
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
414
394
  }
415
395
  
416
396
  /* Seek back to the beginning of the GPGME plaintext data buffer */
423
403
  *plaintext = NULL;
424
404
  while(true){
425
405
    plaintext_capacity = incbuffer(plaintext,
426
 
                                   (size_t)plaintext_length,
427
 
                                   plaintext_capacity);
 
406
                                      (size_t)plaintext_length,
 
407
                                      plaintext_capacity);
428
408
    if(plaintext_capacity == 0){
429
 
      perror_plus("incbuffer");
430
 
      plaintext_length = -1;
431
 
      goto decrypt_end;
 
409
        perror_plus("incbuffer");
 
410
        plaintext_length = -1;
 
411
        goto decrypt_end;
432
412
    }
433
413
    
434
414
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
447
427
  }
448
428
  
449
429
  if(debug){
450
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
430
    fprintf(stderr, "Decrypted password is: ");
451
431
    for(ssize_t i = 0; i < plaintext_length; i++){
452
432
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
453
433
    }
475
455
/* GnuTLS log function callback */
476
456
static void debuggnutls(__attribute__((unused)) int level,
477
457
                        const char* string){
478
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
458
  fprintf(stderr, "GnuTLS: %s", string);
479
459
}
480
460
 
481
461
static int init_gnutls_global(const char *pubkeyfilename,
483
463
  int ret;
484
464
  
485
465
  if(debug){
486
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
466
    fprintf(stderr, "Initializing GnuTLS\n");
487
467
  }
488
468
  
489
469
  ret = gnutls_global_init();
490
470
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
492
 
                 safer_gnutls_strerror(ret));
 
471
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
472
            safer_gnutls_strerror(ret));
493
473
    return -1;
494
474
  }
495
475
  
504
484
  /* OpenPGP credentials */
505
485
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
506
486
  if(ret != GNUTLS_E_SUCCESS){
507
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
508
 
                 safer_gnutls_strerror(ret));
 
487
    fprintf(stderr, "GnuTLS memory error: %s\n",
 
488
            safer_gnutls_strerror(ret));
509
489
    gnutls_global_deinit();
510
490
    return -1;
511
491
  }
512
492
  
513
493
  if(debug){
514
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
515
 
                 " secret key %s as GnuTLS credentials\n",
516
 
                 pubkeyfilename,
517
 
                 seckeyfilename);
 
494
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
495
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
496
            seckeyfilename);
518
497
  }
519
498
  
520
499
  ret = gnutls_certificate_set_openpgp_key_file
521
500
    (mc.cred, pubkeyfilename, seckeyfilename,
522
501
     GNUTLS_OPENPGP_FMT_BASE64);
523
502
  if(ret != GNUTLS_E_SUCCESS){
524
 
    fprintf_plus(stderr,
525
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
526
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
527
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
528
 
                 safer_gnutls_strerror(ret));
 
503
    fprintf(stderr,
 
504
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
505
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
506
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
507
            safer_gnutls_strerror(ret));
529
508
    goto globalfail;
530
509
  }
531
510
  
532
511
  /* GnuTLS server initialization */
533
512
  ret = gnutls_dh_params_init(&mc.dh_params);
534
513
  if(ret != GNUTLS_E_SUCCESS){
535
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
536
 
                 " initialization: %s\n",
537
 
                 safer_gnutls_strerror(ret));
 
514
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
515
            " %s\n", safer_gnutls_strerror(ret));
538
516
    goto globalfail;
539
517
  }
540
518
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
541
519
  if(ret != GNUTLS_E_SUCCESS){
542
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
543
 
                 safer_gnutls_strerror(ret));
 
520
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
521
            safer_gnutls_strerror(ret));
544
522
    goto globalfail;
545
523
  }
546
524
  
566
544
    }
567
545
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
568
546
  if(ret != GNUTLS_E_SUCCESS){
569
 
    fprintf_plus(stderr,
570
 
                 "Error in GnuTLS session initialization: %s\n",
571
 
                 safer_gnutls_strerror(ret));
 
547
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
548
            safer_gnutls_strerror(ret));
572
549
  }
573
550
  
574
551
  {
581
558
      }
582
559
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
583
560
    if(ret != GNUTLS_E_SUCCESS){
584
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
585
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
586
 
                   safer_gnutls_strerror(ret));
 
561
      fprintf(stderr, "Syntax error at: %s\n", err);
 
562
      fprintf(stderr, "GnuTLS error: %s\n",
 
563
              safer_gnutls_strerror(ret));
587
564
      gnutls_deinit(*session);
588
565
      return -1;
589
566
    }
598
575
    }
599
576
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
600
577
  if(ret != GNUTLS_E_SUCCESS){
601
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
602
 
                 safer_gnutls_strerror(ret));
 
578
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
579
            safer_gnutls_strerror(ret));
603
580
    gnutls_deinit(*session);
604
581
    return -1;
605
582
  }
650
627
    pf = PF_INET;
651
628
    break;
652
629
  default:
653
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
630
    fprintf(stderr, "Bad address family: %d\n", af);
654
631
    errno = EINVAL;
655
632
    return -1;
656
633
  }
661
638
  }
662
639
  
663
640
  if(debug){
664
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
665
 
                 PRIu16 "\n", ip, port);
 
641
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
642
            "\n", ip, port);
666
643
  }
667
644
  
668
645
  tcp_sd = socket(pf, SOCK_STREAM, 0);
694
671
  }
695
672
  if(ret == 0){
696
673
    int e = errno;
697
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
674
    fprintf(stderr, "Bad address: %s\n", ip);
698
675
    errno = e;
699
676
    goto mandos_end;
700
677
  }
705
682
    
706
683
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
707
684
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
708
 
                                -Wunreachable-code*/
 
685
                              -Wunreachable-code*/
709
686
      if(if_index == AVAHI_IF_UNSPEC){
710
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
711
 
                     " incomplete without a network interface\n");
 
687
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
688
                " without a network interface\n");
712
689
        errno = EINVAL;
713
690
        goto mandos_end;
714
691
      }
732
709
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
733
710
        perror_plus("if_indextoname");
734
711
      } else {
735
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
736
 
                     "\n", ip, interface, port);
 
712
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
713
                ip, interface, port);
737
714
      }
738
715
    } else {
739
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
740
 
                   ip, port);
 
716
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
717
              port);
741
718
    }
742
719
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
743
720
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
753
730
      perror_plus("inet_ntop");
754
731
    } else {
755
732
      if(strcmp(addrstr, ip) != 0){
756
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
733
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
757
734
      }
758
735
    }
759
736
  }
787
764
  while(true){
788
765
    size_t out_size = strlen(out);
789
766
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
790
 
                                        out_size - written));
 
767
                                   out_size - written));
791
768
    if(ret == -1){
792
769
      int e = errno;
793
770
      perror_plus("write");
813
790
  }
814
791
  
815
792
  if(debug){
816
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
793
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
817
794
  }
818
795
  
819
796
  if(quit_now){
839
816
  
840
817
  if(ret != GNUTLS_E_SUCCESS){
841
818
    if(debug){
842
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
819
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
843
820
      gnutls_perror(ret);
844
821
    }
845
822
    errno = EPROTO;
849
826
  /* Read OpenPGP packet that contains the wanted password */
850
827
  
851
828
  if(debug){
852
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
853
 
                 " %s\n", ip);
 
829
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
830
            ip);
854
831
  }
855
832
  
856
833
  while(true){
861
838
    }
862
839
    
863
840
    buffer_capacity = incbuffer(&buffer, buffer_length,
864
 
                                buffer_capacity);
 
841
                                   buffer_capacity);
865
842
    if(buffer_capacity == 0){
866
843
      int e = errno;
867
844
      perror_plus("incbuffer");
894
871
          }
895
872
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
896
873
        if(ret < 0){
897
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
898
 
                       "***\n");
 
874
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
899
875
          gnutls_perror(ret);
900
876
          errno = EPROTO;
901
877
          goto mandos_end;
902
878
        }
903
879
        break;
904
880
      default:
905
 
        fprintf_plus(stderr, "Unknown error while reading data from"
906
 
                     " encrypted session with Mandos server\n");
 
881
        fprintf(stderr, "Unknown error while reading data from"
 
882
                " encrypted session with Mandos server\n");
907
883
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
908
884
        errno = EIO;
909
885
        goto mandos_end;
914
890
  }
915
891
  
916
892
  if(debug){
917
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
893
    fprintf(stderr, "Closing TLS session\n");
918
894
  }
919
895
  
920
896
  if(quit_now){
932
908
  
933
909
  if(buffer_length > 0){
934
910
    ssize_t decrypted_buffer_size;
935
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
911
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
912
                                               buffer_length,
936
913
                                               &decrypted_buffer);
937
914
    if(decrypted_buffer_size >= 0){
938
915
      
949
926
        if(ret == 0 and ferror(stdout)){
950
927
          int e = errno;
951
928
          if(debug){
952
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
953
 
                         strerror(errno));
 
929
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
930
                    strerror(errno));
954
931
          }
955
932
          errno = e;
956
933
          goto mandos_end;
1013
990
  switch(event){
1014
991
  default:
1015
992
  case AVAHI_RESOLVER_FAILURE:
1016
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1017
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1018
 
                 domain,
1019
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
993
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
994
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
995
            avahi_strerror(avahi_server_errno(mc.server)));
1020
996
    break;
1021
997
    
1022
998
  case AVAHI_RESOLVER_FOUND:
1024
1000
      char ip[AVAHI_ADDRESS_STR_MAX];
1025
1001
      avahi_address_snprint(ip, sizeof(ip), address);
1026
1002
      if(debug){
1027
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1028
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1029
 
                     host_name, ip, (intmax_t)interface, port);
 
1003
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1004
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1005
                ip, (intmax_t)interface, port);
1030
1006
      }
1031
1007
      int ret = start_mandos_communication(ip, port, interface,
1032
1008
                                           avahi_proto_to_af(proto));
1033
1009
      if(ret == 0){
1034
1010
        avahi_simple_poll_quit(mc.simple_poll);
1035
1011
      } else {
1036
 
        if(not add_server(ip, port, interface,
1037
 
                          avahi_proto_to_af(proto))){
1038
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1039
 
                       " list\n", name);
1040
 
        }
 
1012
        ret = add_server(ip, port, interface,
 
1013
                         avahi_proto_to_af(proto));
1041
1014
      }
1042
1015
    }
1043
1016
  }
1067
1040
  default:
1068
1041
  case AVAHI_BROWSER_FAILURE:
1069
1042
    
1070
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1071
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1043
    fprintf(stderr, "(Avahi browser) %s\n",
 
1044
            avahi_strerror(avahi_server_errno(mc.server)));
1072
1045
    avahi_simple_poll_quit(mc.simple_poll);
1073
1046
    return;
1074
1047
    
1081
1054
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1082
1055
                                    name, type, domain, protocol, 0,
1083
1056
                                    resolve_callback, NULL) == NULL)
1084
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1085
 
                   " %s\n", name,
1086
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
1057
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1058
              name, avahi_strerror(avahi_server_errno(mc.server)));
1087
1059
    break;
1088
1060
    
1089
1061
  case AVAHI_BROWSER_REMOVE:
1092
1064
  case AVAHI_BROWSER_ALL_FOR_NOW:
1093
1065
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1094
1066
    if(debug){
1095
 
      fprintf_plus(stderr, "No Mandos server found, still"
1096
 
                   " searching...\n");
 
1067
      fprintf(stderr, "No Mandos server found, still searching...\n");
1097
1068
    }
1098
1069
    break;
1099
1070
  }
1114
1085
  errno = old_errno;
1115
1086
}
1116
1087
 
1117
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1118
 
  int ret;
1119
 
  
1120
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1121
 
  if(s < 0){
1122
 
    perror_plus("socket");
1123
 
    return false;
1124
 
  }
1125
 
  strcpy(ifr->ifr_name, ifname);
1126
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1127
 
  if(ret == -1){
 
1088
/* 
 
1089
 * This function determines if a directory entry in /sys/class/net
 
1090
 * corresponds to an acceptable network device.
 
1091
 * (This function is passed to scandir(3) as a filter function.)
 
1092
 */
 
1093
int good_interface(const struct dirent *if_entry){
 
1094
  ssize_t ssret;
 
1095
  char *flagname = NULL;
 
1096
  if(if_entry->d_name[0] == '.'){
 
1097
    return 0;
 
1098
  }
 
1099
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1100
                     if_entry->d_name);
 
1101
  if(ret < 0){
 
1102
    perror_plus("asprintf");
 
1103
    return 0;
 
1104
  }
 
1105
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1106
  if(flags_fd == -1){
 
1107
    perror_plus("open");
 
1108
    free(flagname);
 
1109
    return 0;
 
1110
  }
 
1111
  free(flagname);
 
1112
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1113
  /* read line from flags_fd */
 
1114
  ssize_t to_read = 2+(sizeof(ifreq_flags)*2)+1; /* "0x1003\n" */
 
1115
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1116
  flagstring[(size_t)to_read] = '\0';
 
1117
  if(flagstring == NULL){
 
1118
    perror_plus("malloc");
 
1119
    close(flags_fd);
 
1120
    return 0;
 
1121
  }
 
1122
  while(to_read > 0){
 
1123
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1124
                                             (size_t)to_read));
 
1125
    if(ssret == -1){
 
1126
      perror_plus("read");
 
1127
      free(flagstring);
 
1128
      close(flags_fd);
 
1129
      return 0;
 
1130
    }
 
1131
    to_read -= ssret;
 
1132
    if(ssret == 0){
 
1133
      break;
 
1134
    }
 
1135
  }
 
1136
  close(flags_fd);
 
1137
  intmax_t tmpmax;
 
1138
  char *tmp;
 
1139
  errno = 0;
 
1140
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1141
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1142
                                         and not (isspace(*tmp)))
 
1143
     or tmpmax != (ifreq_flags)tmpmax){
1128
1144
    if(debug){
1129
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1145
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1146
              flagstring, if_entry->d_name);
1130
1147
    }
1131
 
    return false;
 
1148
    free(flagstring);
 
1149
    return 0;
1132
1150
  }
1133
 
  return true;
1134
 
}
1135
 
 
1136
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1137
 
  
 
1151
  free(flagstring);
 
1152
  ifreq_flags flags = (ifreq_flags)tmpmax;
1138
1153
  /* Reject the loopback device */
1139
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1154
  if(flags & IFF_LOOPBACK){
1140
1155
    if(debug){
1141
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1142
 
                   ifname);
 
1156
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1157
              if_entry->d_name);
1143
1158
    }
1144
 
    return false;
 
1159
    return 0;
1145
1160
  }
1146
1161
  /* Accept point-to-point devices only if connect_to is specified */
1147
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1162
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1148
1163
    if(debug){
1149
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1150
 
                   " \"%s\"\n", ifname);
 
1164
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1165
              if_entry->d_name);
1151
1166
    }
1152
 
    return true;
 
1167
    return 1;
1153
1168
  }
1154
1169
  /* Otherwise, reject non-broadcast-capable devices */
1155
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1170
  if(not (flags & IFF_BROADCAST)){
1156
1171
    if(debug){
1157
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1158
 
                   " \"%s\"\n", ifname);
 
1172
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1173
              if_entry->d_name);
1159
1174
    }
1160
 
    return false;
 
1175
    return 0;
1161
1176
  }
1162
1177
  /* Reject non-ARP interfaces (including dummy interfaces) */
1163
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1178
  if(flags & IFF_NOARP){
1164
1179
    if(debug){
1165
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1166
 
                   ifname);
 
1180
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1181
              if_entry->d_name);
1167
1182
    }
1168
 
    return false;
 
1183
    return 0;
1169
1184
  }
1170
 
  
1171
1185
  /* Accept this device */
1172
1186
  if(debug){
1173
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1174
 
  }
1175
 
  return true;
1176
 
}
1177
 
 
1178
 
/* 
1179
 
 * This function determines if a directory entry in /sys/class/net
1180
 
 * corresponds to an acceptable network device.
1181
 
 * (This function is passed to scandir(3) as a filter function.)
1182
 
 */
1183
 
int good_interface(const struct dirent *if_entry){
1184
 
  if(if_entry->d_name[0] == '.'){
1185
 
    return 0;
1186
 
  }
1187
 
  
1188
 
  struct ifreq ifr;
1189
 
  if(not get_flags(if_entry->d_name, &ifr)){
1190
 
    if(debug){
1191
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1192
 
                   "\"%s\"\n", if_entry->d_name);
1193
 
    }
1194
 
    return 0;
1195
 
  }
1196
 
  
1197
 
  if(not good_flags(if_entry->d_name, &ifr)){
1198
 
    return 0;
1199
 
  }
1200
 
  return 1;
1201
 
}
1202
 
 
1203
 
/* 
1204
 
 * This function determines if a directory entry in /sys/class/net
1205
 
 * corresponds to an acceptable network device which is up.
1206
 
 * (This function is passed to scandir(3) as a filter function.)
1207
 
 */
1208
 
int up_interface(const struct dirent *if_entry){
1209
 
  if(if_entry->d_name[0] == '.'){
1210
 
    return 0;
1211
 
  }
1212
 
  
1213
 
  struct ifreq ifr;
1214
 
  if(not get_flags(if_entry->d_name, &ifr)){
1215
 
    if(debug){
1216
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1217
 
                   "\"%s\"\n", if_entry->d_name);
1218
 
    }
1219
 
    return 0;
1220
 
  }
1221
 
  
1222
 
  /* Reject down interfaces */
1223
 
  if(not (ifr.ifr_flags & IFF_UP)){
1224
 
    if(debug){
1225
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1226
 
                   if_entry->d_name);
1227
 
    }
1228
 
    return 0;
1229
 
  }
1230
 
  
1231
 
  /* Reject non-running interfaces */
1232
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1233
 
    if(debug){
1234
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1235
 
                   if_entry->d_name);
1236
 
    }
1237
 
    return 0;
1238
 
  }
1239
 
  
1240
 
  if(not good_flags(if_entry->d_name, &ifr)){
1241
 
    return 0;
 
1187
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1188
            if_entry->d_name);
1242
1189
  }
1243
1190
  return 1;
1244
1191
}
1254
1201
  return 1;
1255
1202
}
1256
1203
 
1257
 
/* Is this directory entry a runnable program? */
1258
 
int runnable_hook(const struct dirent *direntry){
1259
 
  int ret;
1260
 
  size_t sret;
1261
 
  struct stat st;
1262
 
  
1263
 
  if((direntry->d_name)[0] == '\0'){
1264
 
    /* Empty name? */
1265
 
    return 0;
1266
 
  }
1267
 
  
1268
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1269
 
                "abcdefghijklmnopqrstuvwxyz"
1270
 
                "0123456789"
1271
 
                "_-");
1272
 
  if((direntry->d_name)[sret] != '\0'){
1273
 
    /* Contains non-allowed characters */
1274
 
    if(debug){
1275
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1276
 
                   direntry->d_name);
1277
 
    }
1278
 
    return 0;
1279
 
  }
1280
 
  
1281
 
  char *fullname = NULL;
1282
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1283
 
  if(ret < 0){
1284
 
    perror_plus("asprintf");
1285
 
    return 0;
1286
 
  }
1287
 
  
1288
 
  ret = stat(fullname, &st);
1289
 
  if(ret == -1){
1290
 
    if(debug){
1291
 
      perror_plus("Could not stat hook");
1292
 
    }
1293
 
    return 0;
1294
 
  }
1295
 
  if(not (S_ISREG(st.st_mode))){
1296
 
    /* Not a regular file */
1297
 
    if(debug){
1298
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1299
 
                   direntry->d_name);
1300
 
    }
1301
 
    return 0;
1302
 
  }
1303
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1304
 
    /* Not executable */
1305
 
    if(debug){
1306
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1307
 
                   direntry->d_name);
1308
 
    }
1309
 
    return 0;
1310
 
  }
1311
 
  if(debug){
1312
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1313
 
                 direntry->d_name);
1314
 
  }
1315
 
  return 1;
1316
 
}
1317
 
 
1318
1204
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1319
1205
  int ret;
1320
1206
  struct timespec now;
1324
1210
  while(true){
1325
1211
    if(mc.current_server == NULL){
1326
1212
      if (debug){
1327
 
        fprintf_plus(stderr, "Wait until first server is found."
1328
 
                     " No timeout!\n");
 
1213
        fprintf(stderr,
 
1214
                "Wait until first server is found. No timeout!\n");
1329
1215
      }
1330
1216
      ret = avahi_simple_poll_iterate(s, -1);
1331
1217
    } else {
1332
1218
      if (debug){
1333
 
        fprintf_plus(stderr, "Check current_server if we should run"
1334
 
                     " it, or wait\n");
 
1219
        fprintf(stderr, "Check current_server if we should run it,"
 
1220
                " or wait\n");
1335
1221
      }
1336
1222
      /* the current time */
1337
1223
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1353
1239
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1354
1240
      
1355
1241
      if (debug){
1356
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1357
 
                     block_time);
 
1242
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
1358
1243
      }
1359
1244
      
1360
1245
      if(block_time <= 0){
1380
1265
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1381
1266
    }
1382
1267
    if(ret != 0){
1383
 
      if (ret > 0 or errno != EINTR){
 
1268
      if (ret > 0 or errno != EINTR) {
1384
1269
        return (ret != 1) ? ret : 0;
1385
1270
      }
1386
1271
    }
1387
1272
  }
1388
1273
}
1389
1274
 
1390
 
bool run_network_hooks(const char *mode, const char *interface,
1391
 
                       const float delay){
1392
 
  struct dirent **direntries;
1393
 
  struct dirent *direntry;
1394
 
  int ret;
1395
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1396
 
                         alphasort);
1397
 
  if(numhooks == -1){
1398
 
    perror_plus("scandir");
1399
 
  } else {
1400
 
    int devnull = open("/dev/null", O_RDONLY);
1401
 
    for(int i = 0; i < numhooks; i++){
1402
 
      direntry = direntries[i];
1403
 
      char *fullname = NULL;
1404
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1405
 
      if(ret < 0){
1406
 
        perror_plus("asprintf");
1407
 
        continue;
1408
 
      }
1409
 
      if(debug){
1410
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1411
 
                     direntry->d_name);
1412
 
      }
1413
 
      pid_t hook_pid = fork();
1414
 
      if(hook_pid == 0){
1415
 
        /* Child */
1416
 
        /* Raise privileges */
1417
 
        errno = 0;
1418
 
        ret = seteuid(0);
1419
 
        if(ret == -1){
1420
 
          perror_plus("seteuid");
1421
 
        }
1422
 
        /* Raise privileges even more */
1423
 
        errno = 0;
1424
 
        ret = setuid(0);
1425
 
        if(ret == -1){
1426
 
          perror_plus("setuid");
1427
 
        }
1428
 
        /* Set group */
1429
 
        errno = 0;
1430
 
        ret = setgid(0);
1431
 
        if(ret == -1){
1432
 
          perror_plus("setgid");
1433
 
        }
1434
 
        /* Reset supplementary groups */
1435
 
        errno = 0;
1436
 
        ret = setgroups(0, NULL);
1437
 
        if(ret == -1){
1438
 
          perror_plus("setgroups");
1439
 
        }
1440
 
        dup2(devnull, STDIN_FILENO);
1441
 
        close(devnull);
1442
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1443
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1444
 
        if(ret == -1){
1445
 
          perror_plus("setenv");
1446
 
          _exit(EX_OSERR);
1447
 
        }
1448
 
        ret = setenv("DEVICE", interface, 1);
1449
 
        if(ret == -1){
1450
 
          perror_plus("setenv");
1451
 
          _exit(EX_OSERR);
1452
 
        }
1453
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1454
 
        if(ret == -1){
1455
 
          perror_plus("setenv");
1456
 
          _exit(EX_OSERR);
1457
 
        }
1458
 
        ret = setenv("MODE", mode, 1);
1459
 
        if(ret == -1){
1460
 
          perror_plus("setenv");
1461
 
          _exit(EX_OSERR);
1462
 
        }
1463
 
        char *delaystring;
1464
 
        ret = asprintf(&delaystring, "%f", delay);
1465
 
        if(ret == -1){
1466
 
          perror_plus("asprintf");
1467
 
          _exit(EX_OSERR);
1468
 
        }
1469
 
        ret = setenv("DELAY", delaystring, 1);
1470
 
        if(ret == -1){
1471
 
          free(delaystring);
1472
 
          perror_plus("setenv");
1473
 
          _exit(EX_OSERR);
1474
 
        }
1475
 
        free(delaystring);
1476
 
        if(connect_to != NULL){
1477
 
          ret = setenv("CONNECT", connect_to, 1);
1478
 
          if(ret == -1){
1479
 
            perror_plus("setenv");
1480
 
            _exit(EX_OSERR);
1481
 
          }
1482
 
        }
1483
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1484
 
          perror_plus("execl");
1485
 
          _exit(EXIT_FAILURE);
1486
 
        }
1487
 
      } else {
1488
 
        int status;
1489
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1490
 
          perror_plus("waitpid");
1491
 
          free(fullname);
1492
 
          continue;
1493
 
        }
1494
 
        if(WIFEXITED(status)){
1495
 
          if(WEXITSTATUS(status) != 0){
1496
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1497
 
                         " with status %d\n", direntry->d_name,
1498
 
                         WEXITSTATUS(status));
1499
 
            free(fullname);
1500
 
            continue;
1501
 
          }
1502
 
        } else if(WIFSIGNALED(status)){
1503
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1504
 
                       " signal %d\n", direntry->d_name,
1505
 
                       WTERMSIG(status));
1506
 
          free(fullname);
1507
 
          continue;
1508
 
        } else {
1509
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1510
 
                       " crashed\n", direntry->d_name);
1511
 
          free(fullname);
1512
 
          continue;
1513
 
        }
1514
 
      }
1515
 
      free(fullname);
1516
 
      if(debug){
1517
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1518
 
                     direntry->d_name);
1519
 
      }
1520
 
    }
1521
 
    close(devnull);
1522
 
  }
1523
 
  return true;
1524
 
}
1525
 
 
1526
1275
int main(int argc, char *argv[]){
1527
1276
  AvahiSServiceBrowser *sb = NULL;
1528
1277
  int error;
1608
1357
        .group = 2 },
1609
1358
      { .name = "retry", .key = 132,
1610
1359
        .arg = "SECONDS",
1611
 
        .doc = "Retry interval used when denied by the Mandos server",
1612
 
        .group = 2 },
1613
 
      { .name = "network-hook-dir", .key = 133,
1614
 
        .arg = "DIR",
1615
 
        .doc = "Directory where network hooks are located",
 
1360
        .doc = "Retry interval used when denied by the mandos server",
1616
1361
        .group = 2 },
1617
1362
      /*
1618
1363
       * These reproduce what we would get without ARGP_NO_HELP
1672
1417
          argp_error(state, "Bad retry interval");
1673
1418
        }
1674
1419
        break;
1675
 
      case 133:                 /* --network-hook-dir */
1676
 
        hookdir = arg;
1677
 
        break;
1678
1420
        /*
1679
1421
         * These reproduce what we would get without ARGP_NO_HELP
1680
1422
         */
1686
1428
        argp_state_help(state, state->out_stream,
1687
1429
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1688
1430
      case 'V':                 /* --version */
1689
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1431
        fprintf(state->out_stream, "%s\n", argp_program_version);
1690
1432
        exit(argp_err_exit_status);
1691
1433
        break;
1692
1434
      default:
1719
1461
  {
1720
1462
    /* Work around Debian bug #633582:
1721
1463
       <http://bugs.debian.org/633582> */
 
1464
    struct stat st;
1722
1465
    
1723
1466
    /* Re-raise priviliges */
1724
1467
    errno = 0;
1725
1468
    ret = seteuid(0);
1726
1469
    if(ret == -1){
1727
1470
      perror_plus("seteuid");
1728
 
    } else {
1729
 
      struct stat st;
1730
 
      
1731
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1732
 
        int seckey_fd = open(seckey, O_RDONLY);
1733
 
        if(seckey_fd == -1){
1734
 
          perror_plus("open");
1735
 
        } else {
1736
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1737
 
          if(ret == -1){
1738
 
            perror_plus("fstat");
1739
 
          } else {
1740
 
            if(S_ISREG(st.st_mode)
1741
 
               and st.st_uid == 0 and st.st_gid == 0){
1742
 
              ret = fchown(seckey_fd, uid, gid);
1743
 
              if(ret == -1){
1744
 
                perror_plus("fchown");
1745
 
              }
1746
 
            }
1747
 
          }
1748
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1749
 
        }
1750
 
      }
1751
 
    
1752
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1753
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1754
 
        if(pubkey_fd == -1){
1755
 
          perror_plus("open");
1756
 
        } else {
1757
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1758
 
          if(ret == -1){
1759
 
            perror_plus("fstat");
1760
 
          } else {
1761
 
            if(S_ISREG(st.st_mode)
1762
 
               and st.st_uid == 0 and st.st_gid == 0){
1763
 
              ret = fchown(pubkey_fd, uid, gid);
1764
 
              if(ret == -1){
1765
 
                perror_plus("fchown");
1766
 
              }
1767
 
            }
1768
 
          }
1769
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1770
 
        }
1771
 
      }
1772
 
    
1773
 
      /* Lower privileges */
1774
 
      errno = 0;
1775
 
      ret = seteuid(uid);
1776
 
      if(ret == -1){
1777
 
        perror_plus("seteuid");
1778
 
      }
1779
 
    }
1780
 
  }
1781
 
  
1782
 
  /* Run network hooks */
1783
 
  if(not run_network_hooks("start", interface, delay)){
1784
 
    goto end;
 
1471
    }
 
1472
    
 
1473
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
1474
      int seckey_fd = open(seckey, O_RDONLY);
 
1475
      if(seckey_fd == -1){
 
1476
        perror_plus("open");
 
1477
      } else {
 
1478
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
1479
        if(ret == -1){
 
1480
          perror_plus("fstat");
 
1481
        } else {
 
1482
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1483
            ret = fchown(seckey_fd, uid, gid);
 
1484
            if(ret == -1){
 
1485
              perror_plus("fchown");
 
1486
            }
 
1487
          }
 
1488
        }
 
1489
        TEMP_FAILURE_RETRY(close(seckey_fd));
 
1490
      }
 
1491
    }
 
1492
    
 
1493
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
1494
      int pubkey_fd = open(pubkey, O_RDONLY);
 
1495
      if(pubkey_fd == -1){
 
1496
        perror_plus("open");
 
1497
      } else {
 
1498
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
1499
        if(ret == -1){
 
1500
          perror_plus("fstat");
 
1501
        } else {
 
1502
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
 
1503
            ret = fchown(pubkey_fd, uid, gid);
 
1504
            if(ret == -1){
 
1505
              perror_plus("fchown");
 
1506
            }
 
1507
          }
 
1508
        }
 
1509
        TEMP_FAILURE_RETRY(close(pubkey_fd));
 
1510
      }
 
1511
    }
 
1512
    
 
1513
    /* Lower privileges */
 
1514
    errno = 0;
 
1515
    ret = seteuid(uid);
 
1516
    if(ret == -1){
 
1517
      perror_plus("seteuid");
 
1518
    }
1785
1519
  }
1786
1520
  
1787
1521
  if(not debug){
1788
1522
    avahi_set_log_function(empty_log);
1789
1523
  }
1790
 
  
 
1524
 
1791
1525
  if(interface[0] == '\0'){
1792
1526
    struct dirent **direntries;
1793
 
    /* First look for interfaces that are up */
1794
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1527
    ret = scandir(sys_class_net, &direntries, good_interface,
1795
1528
                  alphasort);
1796
 
    if(ret == 0){
1797
 
      /* No up interfaces, look for any good interfaces */
1798
 
      free(direntries);
1799
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1800
 
                    alphasort);
1801
 
    }
1802
1529
    if(ret >= 1){
1803
 
      /* Pick the first interface returned */
 
1530
      /* Pick the first good interface */
1804
1531
      interface = strdup(direntries[0]->d_name);
1805
1532
      if(debug){
1806
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1533
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1807
1534
      }
1808
1535
      if(interface == NULL){
1809
1536
        perror_plus("malloc");
1814
1541
      free(direntries);
1815
1542
    } else {
1816
1543
      free(direntries);
1817
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1544
      fprintf(stderr, "Could not find a network interface\n");
1818
1545
      exitcode = EXIT_FAILURE;
1819
1546
      goto end;
1820
1547
    }
1826
1553
  srand((unsigned int) time(NULL));
1827
1554
  mc.simple_poll = avahi_simple_poll_new();
1828
1555
  if(mc.simple_poll == NULL){
1829
 
    fprintf_plus(stderr,
1830
 
                 "Avahi: Failed to create simple poll object.\n");
 
1556
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1831
1557
    exitcode = EX_UNAVAILABLE;
1832
1558
    goto end;
1833
1559
  }
1899
1625
  if(strcmp(interface, "none") != 0){
1900
1626
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1901
1627
    if(if_index == 0){
1902
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1628
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1903
1629
      exitcode = EX_UNAVAILABLE;
1904
1630
      goto end;
1905
1631
    }
2025
1751
#endif  /* __linux__ */
2026
1752
    /* Lower privileges */
2027
1753
    errno = 0;
2028
 
    /* Lower privileges */
2029
 
    ret = seteuid(uid);
2030
 
    if(ret == -1){
2031
 
      perror_plus("seteuid");
 
1754
    if(take_down_interface){
 
1755
      /* Lower privileges */
 
1756
      ret = seteuid(uid);
 
1757
      if(ret == -1){
 
1758
        perror_plus("seteuid");
 
1759
      }
 
1760
    } else {
 
1761
      /* Lower privileges permanently */
 
1762
      ret = setuid(uid);
 
1763
      if(ret == -1){
 
1764
        perror_plus("setuid");
 
1765
      }
2032
1766
    }
2033
1767
  }
2034
1768
  
2038
1772
  
2039
1773
  ret = init_gnutls_global(pubkey, seckey);
2040
1774
  if(ret == -1){
2041
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1775
    fprintf(stderr, "init_gnutls_global failed\n");
2042
1776
    exitcode = EX_UNAVAILABLE;
2043
1777
    goto end;
2044
1778
  } else {
2060
1794
  }
2061
1795
  
2062
1796
  if(not init_gpgme(pubkey, seckey, tempdir)){
2063
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1797
    fprintf(stderr, "init_gpgme failed\n");
2064
1798
    exitcode = EX_UNAVAILABLE;
2065
1799
    goto end;
2066
1800
  } else {
2076
1810
    /* (Mainly meant for debugging) */
2077
1811
    char *address = strrchr(connect_to, ':');
2078
1812
    if(address == NULL){
2079
 
      fprintf_plus(stderr, "No colon in address\n");
 
1813
      fprintf(stderr, "No colon in address\n");
2080
1814
      exitcode = EX_USAGE;
2081
1815
      goto end;
2082
1816
    }
2090
1824
    tmpmax = strtoimax(address+1, &tmp, 10);
2091
1825
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2092
1826
       or tmpmax != (uint16_t)tmpmax){
2093
 
      fprintf_plus(stderr, "Bad port number\n");
 
1827
      fprintf(stderr, "Bad port number\n");
2094
1828
      exitcode = EX_USAGE;
2095
1829
      goto end;
2096
1830
    }
2126
1860
        break;
2127
1861
      }
2128
1862
      if(debug){
2129
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2130
 
                     (int)retry_interval);
 
1863
        fprintf(stderr, "Retrying in %d seconds\n",
 
1864
                (int)retry_interval);
2131
1865
      }
2132
1866
      sleep((int)retry_interval);
2133
1867
    }
2135
1869
    if (not quit_now){
2136
1870
      exitcode = EXIT_SUCCESS;
2137
1871
    }
2138
 
    
 
1872
 
2139
1873
    goto end;
2140
1874
  }
2141
1875
  
2163
1897
  
2164
1898
  /* Check if creating the Avahi server object succeeded */
2165
1899
  if(mc.server == NULL){
2166
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2167
 
                 avahi_strerror(error));
 
1900
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1901
            avahi_strerror(error));
2168
1902
    exitcode = EX_UNAVAILABLE;
2169
1903
    goto end;
2170
1904
  }
2178
1912
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2179
1913
                                   NULL, 0, browse_callback, NULL);
2180
1914
  if(sb == NULL){
2181
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2182
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1915
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1916
            avahi_strerror(avahi_server_errno(mc.server)));
2183
1917
    exitcode = EX_UNAVAILABLE;
2184
1918
    goto end;
2185
1919
  }
2191
1925
  /* Run the main loop */
2192
1926
  
2193
1927
  if(debug){
2194
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
1928
    fprintf(stderr, "Starting Avahi loop search\n");
2195
1929
  }
2196
1930
 
2197
1931
  ret = avahi_loop_with_timeout(mc.simple_poll,
2198
1932
                                (int)(retry_interval * 1000));
2199
1933
  if(debug){
2200
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2201
 
                 (ret == 0) ? "successfully" : "with error");
 
1934
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1935
            (ret == 0) ? "successfully" : "with error");
2202
1936
  }
2203
1937
  
2204
1938
 end:
2205
1939
  
2206
1940
  if(debug){
2207
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1941
    fprintf(stderr, "%s exiting\n", argv[0]);
2208
1942
  }
2209
1943
  
2210
1944
  /* Cleanup things */
2226
1960
  if(gpgme_initialized){
2227
1961
    gpgme_release(mc.ctx);
2228
1962
  }
2229
 
  
 
1963
 
2230
1964
  /* Cleans up the circular linked list of Mandos servers the client
2231
1965
     has seen */
2232
1966
  if(mc.current_server != NULL){
2238
1972
    }
2239
1973
  }
2240
1974
  
2241
 
  /* Run network hooks */
2242
 
  run_network_hooks("stop", interface, delay);
2243
 
  
2244
 
  /* Re-raise priviliges */
2245
 
  {
 
1975
  /* Take down the network interface */
 
1976
  if(take_down_interface){
 
1977
    /* Re-raise priviliges */
2246
1978
    errno = 0;
2247
1979
    ret = seteuid(0);
2248
1980
    if(ret == -1){
2249
1981
      perror_plus("seteuid");
2250
1982
    }
2251
 
    
2252
 
    /* Take down the network interface */
2253
 
    if(take_down_interface and geteuid() == 0){
 
1983
    if(geteuid() == 0){
2254
1984
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2255
1985
      if(ret == -1){
2256
1986
        perror_plus("ioctl SIOCGIFFLAGS");
2257
 
      } else if(network.ifr_flags & IFF_UP){
 
1987
      } else if(network.ifr_flags & IFF_UP) {
2258
1988
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2259
1989
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2260
1990
        if(ret == -1){
2265
1995
      if(ret == -1){
2266
1996
        perror_plus("close");
2267
1997
      }
 
1998
      /* Lower privileges permanently */
 
1999
      errno = 0;
 
2000
      ret = setuid(uid);
 
2001
      if(ret == -1){
 
2002
        perror_plus("setuid");
 
2003
      }
2268
2004
    }
2269
2005
  }
2270
 
  /* Lower privileges permanently */
2271
 
  errno = 0;
2272
 
  ret = setuid(uid);
2273
 
  if(ret == -1){
2274
 
    perror_plus("setuid");
2275
 
  }
2276
2006
  
2277
2007
  /* Removes the GPGME temp directory and all files inside */
2278
2008
  if(tempdir_created){
2292
2022
        }
2293
2023
        ret = remove(fullname);
2294
2024
        if(ret == -1){
2295
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2296
 
                       strerror(errno));
 
2025
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
2026
                  strerror(errno));
2297
2027
        }
2298
2028
        free(fullname);
2299
2029
      }