/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2011-12-31 20:07:11 UTC
  • mfrom: (535.1.9 wireless-network-hook)
  • Revision ID: teddy@recompile.se-20111231200711-6dli3r8drftem57r
Merge new wireless network hook.  Fix bridge network hook to use
hardware addresses instead of interface names.  Implement and document
new "CONNECT" environment variable for network hooks.

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() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
 
76
                                   setgid(), pause(), _exit() */
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() */
88
91
 
89
92
#ifdef __linux__
90
93
#include <sys/klog.h>           /* klogctl() */
108
111
                                   init_gnutls_session(),
109
112
                                   GNUTLS_* */
110
113
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
114
                         /* gnutls_certificate_set_openpgp_key_file(),
 
115
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
116
 
114
117
/* GPGME */
115
118
#include <gpgme.h>              /* All GPGME types, constants and
123
126
#define PATHDIR "/conf/conf.d/mandos"
124
127
#define SECKEY "seckey.txt"
125
128
#define PUBKEY "pubkey.txt"
 
129
#define HOOKDIR "/lib/mandos/network-hooks.d"
126
130
 
127
131
bool debug = false;
128
132
static const char mandos_protocol_version[] = "1";
129
133
const char *argp_program_version = "mandos-client " VERSION;
130
 
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
 
134
const char *argp_program_bug_address = "<mandos@recompile.se>";
131
135
static const char sys_class_net[] = "/sys/class/net";
132
136
char *connect_to = NULL;
 
137
const char *hookdir = HOOKDIR;
133
138
 
134
139
/* Doubly linked list that need to be circularly linked when used */
135
140
typedef struct server{
165
170
 
166
171
/* Function to use when printing errors */
167
172
void perror_plus(const char *print_text){
 
173
  int e = errno;
168
174
  fprintf(stderr, "Mandos plugin %s: ",
169
175
          program_invocation_short_name);
 
176
  errno = e;
170
177
  perror(print_text);
171
178
}
172
179
 
 
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
 
173
190
/*
174
191
 * Make additional room in "buffer" for at least BUFFER_SIZE more
175
192
 * bytes. "buffer_capacity" is how much is currently allocated,
176
193
 * "buffer_length" is how much is already used.
177
194
 */
178
195
size_t incbuffer(char **buffer, size_t buffer_length,
179
 
                  size_t buffer_capacity){
 
196
                 size_t buffer_capacity){
180
197
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
181
198
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
182
199
    if(buffer == NULL){
187
204
  return buffer_capacity;
188
205
}
189
206
 
190
 
int add_server(const char *ip, uint16_t port,
191
 
                 AvahiIfIndex if_index,
192
 
                 int af){
 
207
/* 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){
193
210
  int ret;
194
211
  server *new_server = malloc(sizeof(server));
195
212
  if(new_server == NULL){
196
213
    perror_plus("malloc");
197
 
    return -1;
 
214
    return false;
198
215
  }
199
216
  *new_server = (server){ .ip = strdup(ip),
200
 
                         .port = port,
201
 
                         .if_index = if_index,
202
 
                         .af = af };
 
217
                          .port = port,
 
218
                          .if_index = if_index,
 
219
                          .af = af };
203
220
  if(new_server->ip == NULL){
204
221
    perror_plus("strdup");
205
 
    return -1;
 
222
    return false;
206
223
  }
207
 
  /* unique case of first server */
 
224
  /* Special case of first server */
208
225
  if (mc.current_server == NULL){
209
226
    new_server->next = new_server;
210
227
    new_server->prev = new_server;
211
228
    mc.current_server = new_server;
212
 
  /* Placing the new server last in the list */
 
229
  /* Place the new server last in the list */
213
230
  } else {
214
231
    new_server->next = mc.current_server;
215
232
    new_server->prev = mc.current_server->prev;
219
236
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
220
237
  if(ret == -1){
221
238
    perror_plus("clock_gettime");
222
 
    return -1;
 
239
    return false;
223
240
  }
224
 
  return 0;
 
241
  return true;
225
242
}
226
243
 
227
244
/* 
228
245
 * Initialize GPGME.
229
246
 */
230
 
static bool init_gpgme(const char *seckey,
231
 
                       const char *pubkey, const char *tempdir){
 
247
static bool init_gpgme(const char *seckey, const char *pubkey,
 
248
                       const char *tempdir){
232
249
  gpgme_error_t rc;
233
250
  gpgme_engine_info_t engine_info;
234
251
  
249
266
    
250
267
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
251
268
    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));
 
269
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
270
                   gpgme_strsource(rc), gpgme_strerror(rc));
254
271
      return false;
255
272
    }
256
273
    
257
274
    rc = gpgme_op_import(mc.ctx, pgp_data);
258
275
    if(rc != GPG_ERR_NO_ERROR){
259
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
260
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
276
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
277
                   gpgme_strsource(rc), gpgme_strerror(rc));
261
278
      return false;
262
279
    }
263
280
    
270
287
  }
271
288
  
272
289
  if(debug){
273
 
    fprintf(stderr, "Initializing GPGME\n");
 
290
    fprintf_plus(stderr, "Initializing GPGME\n");
274
291
  }
275
292
  
276
293
  /* Init GPGME */
277
294
  gpgme_check_version(NULL);
278
295
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
279
296
  if(rc != GPG_ERR_NO_ERROR){
280
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
281
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
297
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
298
                 gpgme_strsource(rc), gpgme_strerror(rc));
282
299
    return false;
283
300
  }
284
301
  
285
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
302
  /* Set GPGME home directory for the OpenPGP engine only */
286
303
  rc = gpgme_get_engine_info(&engine_info);
287
304
  if(rc != GPG_ERR_NO_ERROR){
288
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
289
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
305
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
306
                 gpgme_strsource(rc), gpgme_strerror(rc));
290
307
    return false;
291
308
  }
292
309
  while(engine_info != NULL){
298
315
    engine_info = engine_info->next;
299
316
  }
300
317
  if(engine_info == NULL){
301
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
318
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
319
                 tempdir);
302
320
    return false;
303
321
  }
304
322
  
305
323
  /* Create new GPGME "context" */
306
324
  rc = gpgme_new(&(mc.ctx));
307
325
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
309
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
326
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
327
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
328
                 gpgme_strerror(rc));
310
329
    return false;
311
330
  }
312
331
  
331
350
  ssize_t plaintext_length = 0;
332
351
  
333
352
  if(debug){
334
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
353
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
335
354
  }
336
355
  
337
356
  /* Create new GPGME data buffer from memory cryptotext */
338
357
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
339
358
                               0);
340
359
  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));
 
360
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
361
                 gpgme_strsource(rc), gpgme_strerror(rc));
343
362
    return -1;
344
363
  }
345
364
  
346
365
  /* Create new empty GPGME data buffer for the plaintext */
347
366
  rc = gpgme_data_new(&dh_plain);
348
367
  if(rc != GPG_ERR_NO_ERROR){
349
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
350
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
368
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
369
                 "bad gpgme_data_new: %s: %s\n",
 
370
                 gpgme_strsource(rc), gpgme_strerror(rc));
351
371
    gpgme_data_release(dh_crypto);
352
372
    return -1;
353
373
  }
356
376
     data buffer */
357
377
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
358
378
  if(rc != GPG_ERR_NO_ERROR){
359
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
360
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
379
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
380
                 gpgme_strsource(rc), gpgme_strerror(rc));
361
381
    plaintext_length = -1;
362
382
    if(debug){
363
383
      gpgme_decrypt_result_t result;
364
384
      result = gpgme_op_decrypt_result(mc.ctx);
365
385
      if(result == NULL){
366
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
386
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
367
387
      } 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);
 
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);
372
392
        if(result->file_name != NULL){
373
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
393
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
374
394
        }
375
395
        gpgme_recipient_t recipient;
376
396
        recipient = result->recipients;
377
397
        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");
 
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");
384
405
          recipient = recipient->next;
385
406
        }
386
407
      }
389
410
  }
390
411
  
391
412
  if(debug){
392
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
413
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
393
414
  }
394
415
  
395
416
  /* Seek back to the beginning of the GPGME plaintext data buffer */
402
423
  *plaintext = NULL;
403
424
  while(true){
404
425
    plaintext_capacity = incbuffer(plaintext,
405
 
                                      (size_t)plaintext_length,
406
 
                                      plaintext_capacity);
 
426
                                   (size_t)plaintext_length,
 
427
                                   plaintext_capacity);
407
428
    if(plaintext_capacity == 0){
408
 
        perror_plus("incbuffer");
409
 
        plaintext_length = -1;
410
 
        goto decrypt_end;
 
429
      perror_plus("incbuffer");
 
430
      plaintext_length = -1;
 
431
      goto decrypt_end;
411
432
    }
412
433
    
413
434
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
426
447
  }
427
448
  
428
449
  if(debug){
429
 
    fprintf(stderr, "Decrypted password is: ");
 
450
    fprintf_plus(stderr, "Decrypted password is: ");
430
451
    for(ssize_t i = 0; i < plaintext_length; i++){
431
452
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
432
453
    }
454
475
/* GnuTLS log function callback */
455
476
static void debuggnutls(__attribute__((unused)) int level,
456
477
                        const char* string){
457
 
  fprintf(stderr, "GnuTLS: %s", string);
 
478
  fprintf_plus(stderr, "GnuTLS: %s", string);
458
479
}
459
480
 
460
481
static int init_gnutls_global(const char *pubkeyfilename,
462
483
  int ret;
463
484
  
464
485
  if(debug){
465
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
486
    fprintf_plus(stderr, "Initializing GnuTLS\n");
466
487
  }
467
488
  
468
489
  ret = gnutls_global_init();
469
490
  if(ret != GNUTLS_E_SUCCESS){
470
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
471
 
            safer_gnutls_strerror(ret));
 
491
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
492
                 safer_gnutls_strerror(ret));
472
493
    return -1;
473
494
  }
474
495
  
483
504
  /* OpenPGP credentials */
484
505
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
485
506
  if(ret != GNUTLS_E_SUCCESS){
486
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
487
 
            safer_gnutls_strerror(ret));
 
507
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
508
                 safer_gnutls_strerror(ret));
488
509
    gnutls_global_deinit();
489
510
    return -1;
490
511
  }
491
512
  
492
513
  if(debug){
493
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
494
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
495
 
            seckeyfilename);
 
514
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
515
                 " secret key %s as GnuTLS credentials\n",
 
516
                 pubkeyfilename,
 
517
                 seckeyfilename);
496
518
  }
497
519
  
498
520
  ret = gnutls_certificate_set_openpgp_key_file
499
521
    (mc.cred, pubkeyfilename, seckeyfilename,
500
522
     GNUTLS_OPENPGP_FMT_BASE64);
501
523
  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));
 
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));
507
529
    goto globalfail;
508
530
  }
509
531
  
510
532
  /* GnuTLS server initialization */
511
533
  ret = gnutls_dh_params_init(&mc.dh_params);
512
534
  if(ret != GNUTLS_E_SUCCESS){
513
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
514
 
            " %s\n", safer_gnutls_strerror(ret));
 
535
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
536
                 " initialization: %s\n",
 
537
                 safer_gnutls_strerror(ret));
515
538
    goto globalfail;
516
539
  }
517
540
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
518
541
  if(ret != GNUTLS_E_SUCCESS){
519
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
520
 
            safer_gnutls_strerror(ret));
 
542
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
543
                 safer_gnutls_strerror(ret));
521
544
    goto globalfail;
522
545
  }
523
546
  
543
566
    }
544
567
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
545
568
  if(ret != GNUTLS_E_SUCCESS){
546
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
547
 
            safer_gnutls_strerror(ret));
 
569
    fprintf_plus(stderr,
 
570
                 "Error in GnuTLS session initialization: %s\n",
 
571
                 safer_gnutls_strerror(ret));
548
572
  }
549
573
  
550
574
  {
557
581
      }
558
582
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
559
583
    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));
 
584
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
585
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
586
                   safer_gnutls_strerror(ret));
563
587
      gnutls_deinit(*session);
564
588
      return -1;
565
589
    }
574
598
    }
575
599
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
576
600
  if(ret != GNUTLS_E_SUCCESS){
577
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
578
 
            safer_gnutls_strerror(ret));
 
601
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
602
                 safer_gnutls_strerror(ret));
579
603
    gnutls_deinit(*session);
580
604
    return -1;
581
605
  }
626
650
    pf = PF_INET;
627
651
    break;
628
652
  default:
629
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
653
    fprintf_plus(stderr, "Bad address family: %d\n", af);
630
654
    errno = EINVAL;
631
655
    return -1;
632
656
  }
637
661
  }
638
662
  
639
663
  if(debug){
640
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
641
 
            "\n", ip, port);
 
664
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
665
                 PRIu16 "\n", ip, port);
642
666
  }
643
667
  
644
668
  tcp_sd = socket(pf, SOCK_STREAM, 0);
670
694
  }
671
695
  if(ret == 0){
672
696
    int e = errno;
673
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
697
    fprintf_plus(stderr, "Bad address: %s\n", ip);
674
698
    errno = e;
675
699
    goto mandos_end;
676
700
  }
681
705
    
682
706
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
683
707
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
684
 
                              -Wunreachable-code*/
 
708
                                -Wunreachable-code*/
685
709
      if(if_index == AVAHI_IF_UNSPEC){
686
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
687
 
                " without a network interface\n");
 
710
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
711
                     " incomplete without a network interface\n");
688
712
        errno = EINVAL;
689
713
        goto mandos_end;
690
714
      }
708
732
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
709
733
        perror_plus("if_indextoname");
710
734
      } else {
711
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
712
 
                ip, interface, port);
 
735
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
736
                     "\n", ip, interface, port);
713
737
      }
714
738
    } else {
715
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
716
 
              port);
 
739
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
740
                   ip, port);
717
741
    }
718
742
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
719
743
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
729
753
      perror_plus("inet_ntop");
730
754
    } else {
731
755
      if(strcmp(addrstr, ip) != 0){
732
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
756
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
733
757
      }
734
758
    }
735
759
  }
763
787
  while(true){
764
788
    size_t out_size = strlen(out);
765
789
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
766
 
                                   out_size - written));
 
790
                                        out_size - written));
767
791
    if(ret == -1){
768
792
      int e = errno;
769
793
      perror_plus("write");
789
813
  }
790
814
  
791
815
  if(debug){
792
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
816
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
793
817
  }
794
818
  
795
819
  if(quit_now){
815
839
  
816
840
  if(ret != GNUTLS_E_SUCCESS){
817
841
    if(debug){
818
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
842
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
819
843
      gnutls_perror(ret);
820
844
    }
821
845
    errno = EPROTO;
825
849
  /* Read OpenPGP packet that contains the wanted password */
826
850
  
827
851
  if(debug){
828
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
829
 
            ip);
 
852
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
853
                 " %s\n", ip);
830
854
  }
831
855
  
832
856
  while(true){
837
861
    }
838
862
    
839
863
    buffer_capacity = incbuffer(&buffer, buffer_length,
840
 
                                   buffer_capacity);
 
864
                                buffer_capacity);
841
865
    if(buffer_capacity == 0){
842
866
      int e = errno;
843
867
      perror_plus("incbuffer");
870
894
          }
871
895
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
872
896
        if(ret < 0){
873
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
897
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
898
                       "***\n");
874
899
          gnutls_perror(ret);
875
900
          errno = EPROTO;
876
901
          goto mandos_end;
877
902
        }
878
903
        break;
879
904
      default:
880
 
        fprintf(stderr, "Unknown error while reading data from"
881
 
                " encrypted session with Mandos server\n");
 
905
        fprintf_plus(stderr, "Unknown error while reading data from"
 
906
                     " encrypted session with Mandos server\n");
882
907
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
883
908
        errno = EIO;
884
909
        goto mandos_end;
889
914
  }
890
915
  
891
916
  if(debug){
892
 
    fprintf(stderr, "Closing TLS session\n");
 
917
    fprintf_plus(stderr, "Closing TLS session\n");
893
918
  }
894
919
  
895
920
  if(quit_now){
907
932
  
908
933
  if(buffer_length > 0){
909
934
    ssize_t decrypted_buffer_size;
910
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
911
 
                                               buffer_length,
 
935
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
912
936
                                               &decrypted_buffer);
913
937
    if(decrypted_buffer_size >= 0){
914
938
      
925
949
        if(ret == 0 and ferror(stdout)){
926
950
          int e = errno;
927
951
          if(debug){
928
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
929
 
                    strerror(errno));
 
952
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
953
                         strerror(errno));
930
954
          }
931
955
          errno = e;
932
956
          goto mandos_end;
989
1013
  switch(event){
990
1014
  default:
991
1015
  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)));
 
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)));
995
1020
    break;
996
1021
    
997
1022
  case AVAHI_RESOLVER_FOUND:
999
1024
      char ip[AVAHI_ADDRESS_STR_MAX];
1000
1025
      avahi_address_snprint(ip, sizeof(ip), address);
1001
1026
      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);
 
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);
1005
1030
      }
1006
1031
      int ret = start_mandos_communication(ip, port, interface,
1007
1032
                                           avahi_proto_to_af(proto));
1008
1033
      if(ret == 0){
1009
1034
        avahi_simple_poll_quit(mc.simple_poll);
1010
1035
      } else {
1011
 
        ret = add_server(ip, port, interface,
1012
 
                         avahi_proto_to_af(proto));
 
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
        }
1013
1041
      }
1014
1042
    }
1015
1043
  }
1039
1067
  default:
1040
1068
  case AVAHI_BROWSER_FAILURE:
1041
1069
    
1042
 
    fprintf(stderr, "(Avahi browser) %s\n",
1043
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1070
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1071
                 avahi_strerror(avahi_server_errno(mc.server)));
1044
1072
    avahi_simple_poll_quit(mc.simple_poll);
1045
1073
    return;
1046
1074
    
1053
1081
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1054
1082
                                    name, type, domain, protocol, 0,
1055
1083
                                    resolve_callback, NULL) == NULL)
1056
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1057
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1084
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1085
                   " %s\n", name,
 
1086
                   avahi_strerror(avahi_server_errno(mc.server)));
1058
1087
    break;
1059
1088
    
1060
1089
  case AVAHI_BROWSER_REMOVE:
1063
1092
  case AVAHI_BROWSER_ALL_FOR_NOW:
1064
1093
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1065
1094
    if(debug){
1066
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1095
      fprintf_plus(stderr, "No Mandos server found, still"
 
1096
                   " searching...\n");
1067
1097
    }
1068
1098
    break;
1069
1099
  }
1084
1114
  errno = old_errno;
1085
1115
}
1086
1116
 
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){
 
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){
1143
1128
    if(debug){
1144
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1145
 
              flagstring, if_entry->d_name);
 
1129
      perror_plus("ioctl SIOCGIFFLAGS");
1146
1130
    }
1147
 
    free(flagstring);
1148
 
    return 0;
 
1131
    return false;
1149
1132
  }
1150
 
  free(flagstring);
1151
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1133
  return true;
 
1134
}
 
1135
 
 
1136
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1137
  
1152
1138
  /* Reject the loopback device */
1153
 
  if(flags & IFF_LOOPBACK){
 
1139
  if(ifr->ifr_flags & IFF_LOOPBACK){
1154
1140
    if(debug){
1155
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1156
 
              if_entry->d_name);
 
1141
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1142
                   ifname);
1157
1143
    }
1158
 
    return 0;
 
1144
    return false;
1159
1145
  }
1160
1146
  /* Accept point-to-point devices only if connect_to is specified */
1161
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1147
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1162
1148
    if(debug){
1163
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1164
 
              if_entry->d_name);
 
1149
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1150
                   " \"%s\"\n", ifname);
1165
1151
    }
1166
 
    return 1;
 
1152
    return true;
1167
1153
  }
1168
1154
  /* Otherwise, reject non-broadcast-capable devices */
1169
 
  if(not (flags & IFF_BROADCAST)){
 
1155
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1170
1156
    if(debug){
1171
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1172
 
              if_entry->d_name);
 
1157
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1158
                   " \"%s\"\n", ifname);
1173
1159
    }
1174
 
    return 0;
 
1160
    return false;
1175
1161
  }
1176
1162
  /* Reject non-ARP interfaces (including dummy interfaces) */
1177
 
  if(flags & IFF_NOARP){
 
1163
  if(ifr->ifr_flags & IFF_NOARP){
1178
1164
    if(debug){
1179
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
1180
 
              if_entry->d_name);
 
1165
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1166
                   ifname);
1181
1167
    }
1182
 
    return 0;
 
1168
    return false;
1183
1169
  }
 
1170
  
1184
1171
  /* Accept this device */
1185
1172
  if(debug){
1186
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1187
 
            if_entry->d_name);
 
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;
1188
1242
  }
1189
1243
  return 1;
1190
1244
}
1200
1254
  return 1;
1201
1255
}
1202
1256
 
 
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
 
1203
1318
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1204
1319
  int ret;
1205
1320
  struct timespec now;
1206
1321
  struct timespec waited_time;
1207
1322
  intmax_t block_time;
1208
 
 
 
1323
  
1209
1324
  while(true){
1210
1325
    if(mc.current_server == NULL){
1211
1326
      if (debug){
1212
 
        fprintf(stderr,
1213
 
                "Wait until first server is found. No timeout!\n");
 
1327
        fprintf_plus(stderr, "Wait until first server is found."
 
1328
                     " No timeout!\n");
1214
1329
      }
1215
1330
      ret = avahi_simple_poll_iterate(s, -1);
1216
1331
    } else {
1217
1332
      if (debug){
1218
 
        fprintf(stderr, "Check current_server if we should run it,"
1219
 
                " or wait\n");
 
1333
        fprintf_plus(stderr, "Check current_server if we should run"
 
1334
                     " it, or wait\n");
1220
1335
      }
1221
1336
      /* the current time */
1222
1337
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1236
1351
      block_time = ((retry_interval
1237
1352
                     - ((intmax_t)waited_time.tv_sec * 1000))
1238
1353
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1239
 
 
 
1354
      
1240
1355
      if (debug){
1241
 
        fprintf(stderr, "Blocking for %ld ms\n", block_time);
 
1356
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1357
                     block_time);
1242
1358
      }
1243
 
 
 
1359
      
1244
1360
      if(block_time <= 0){
1245
1361
        ret = start_mandos_communication(mc.current_server->ip,
1246
1362
                                         mc.current_server->port,
1264
1380
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1265
1381
    }
1266
1382
    if(ret != 0){
1267
 
      if (ret > 0 or errno != EINTR) {
 
1383
      if (ret > 0 or errno != EINTR){
1268
1384
        return (ret != 1) ? ret : 0;
1269
1385
      }
1270
1386
    }
1271
1387
  }
1272
1388
}
1273
1389
 
 
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
 
1274
1526
int main(int argc, char *argv[]){
1275
1527
  AvahiSServiceBrowser *sb = NULL;
1276
1528
  int error;
1356
1608
        .group = 2 },
1357
1609
      { .name = "retry", .key = 132,
1358
1610
        .arg = "SECONDS",
1359
 
        .doc = "Retry interval used when denied by the mandos server",
 
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
1616
        .group = 2 },
1361
1617
      /*
1362
1618
       * These reproduce what we would get without ARGP_NO_HELP
1411
1667
        errno = 0;
1412
1668
        retry_interval = strtod(arg, &tmp);
1413
1669
        if(errno != 0 or tmp == arg or *tmp != '\0'
1414
 
           or (retry_interval * 1000) > INT_MAX){
 
1670
           or (retry_interval * 1000) > INT_MAX
 
1671
           or retry_interval < 0){
1415
1672
          argp_error(state, "Bad retry interval");
1416
1673
        }
1417
1674
        break;
 
1675
      case 133:                 /* --network-hook-dir */
 
1676
        hookdir = arg;
 
1677
        break;
1418
1678
        /*
1419
1679
         * These reproduce what we would get without ARGP_NO_HELP
1420
1680
         */
1426
1686
        argp_state_help(state, state->out_stream,
1427
1687
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1428
1688
      case 'V':                 /* --version */
1429
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
1689
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1430
1690
        exit(argp_err_exit_status);
1431
1691
        break;
1432
1692
      default:
1459
1719
  {
1460
1720
    /* Work around Debian bug #633582:
1461
1721
       <http://bugs.debian.org/633582> */
1462
 
    struct stat st;
1463
1722
    
1464
1723
    /* Re-raise priviliges */
1465
1724
    errno = 0;
1466
1725
    ret = seteuid(0);
1467
1726
    if(ret == -1){
1468
1727
      perror_plus("seteuid");
1469
 
    }
1470
 
    
1471
 
    int seckey_fd = open(PATHDIR "/" SECKEY, O_RDONLY);
1472
 
    if(seckey_fd == -1){
1473
 
      perror_plus("open");
1474
 
    } else {
1475
 
      ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1476
 
      if(ret == -1){
1477
 
        perror_plus("fstat");
1478
 
      } else {
1479
 
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1480
 
          ret = fchown(seckey_fd, uid, gid);
1481
 
          if(ret == -1){
1482
 
            perror_plus("fchown");
1483
 
          }
1484
 
        }
1485
 
      }
1486
 
      TEMP_FAILURE_RETRY(close(seckey_fd));
1487
 
    }
1488
 
    
1489
 
    int pubkey_fd = open(PATHDIR "/" PUBKEY, O_RDONLY);
1490
 
    if(pubkey_fd == -1){
1491
 
      perror_plus("open");
1492
 
    } else {
1493
 
      ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1494
 
      if(ret == -1){
1495
 
        perror_plus("fstat");
1496
 
      } else {
1497
 
        if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1498
 
          ret = fchown(pubkey_fd, uid, gid);
1499
 
          if(ret == -1){
1500
 
            perror_plus("fchown");
1501
 
          }
1502
 
        }
1503
 
      }
1504
 
      TEMP_FAILURE_RETRY(close(pubkey_fd));
1505
 
    }
1506
 
    
1507
 
    /* Lower privileges */
1508
 
    errno = 0;
1509
 
    ret = seteuid(uid);
1510
 
    if(ret == -1){
1511
 
      perror_plus("seteuid");
1512
 
    }
 
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;
1513
1785
  }
1514
1786
  
1515
1787
  if(not debug){
1516
1788
    avahi_set_log_function(empty_log);
1517
1789
  }
1518
 
 
 
1790
  
1519
1791
  if(interface[0] == '\0'){
1520
1792
    struct dirent **direntries;
1521
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1793
    /* First look for interfaces that are up */
 
1794
    ret = scandir(sys_class_net, &direntries, up_interface,
1522
1795
                  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
    }
1523
1802
    if(ret >= 1){
1524
 
      /* Pick the first good interface */
 
1803
      /* Pick the first interface returned */
1525
1804
      interface = strdup(direntries[0]->d_name);
1526
1805
      if(debug){
1527
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1806
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1528
1807
      }
1529
1808
      if(interface == NULL){
1530
1809
        perror_plus("malloc");
1535
1814
      free(direntries);
1536
1815
    } else {
1537
1816
      free(direntries);
1538
 
      fprintf(stderr, "Could not find a network interface\n");
 
1817
      fprintf_plus(stderr, "Could not find a network interface\n");
1539
1818
      exitcode = EXIT_FAILURE;
1540
1819
      goto end;
1541
1820
    }
1547
1826
  srand((unsigned int) time(NULL));
1548
1827
  mc.simple_poll = avahi_simple_poll_new();
1549
1828
  if(mc.simple_poll == NULL){
1550
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1829
    fprintf_plus(stderr,
 
1830
                 "Avahi: Failed to create simple poll object.\n");
1551
1831
    exitcode = EX_UNAVAILABLE;
1552
1832
    goto end;
1553
1833
  }
1619
1899
  if(strcmp(interface, "none") != 0){
1620
1900
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1621
1901
    if(if_index == 0){
1622
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1902
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1623
1903
      exitcode = EX_UNAVAILABLE;
1624
1904
      goto end;
1625
1905
    }
1745
2025
#endif  /* __linux__ */
1746
2026
    /* Lower privileges */
1747
2027
    errno = 0;
1748
 
    if(take_down_interface){
1749
 
      /* Lower privileges */
1750
 
      ret = seteuid(uid);
1751
 
      if(ret == -1){
1752
 
        perror_plus("seteuid");
1753
 
      }
1754
 
    } else {
1755
 
      /* Lower privileges permanently */
1756
 
      ret = setuid(uid);
1757
 
      if(ret == -1){
1758
 
        perror_plus("setuid");
1759
 
      }
 
2028
    /* Lower privileges */
 
2029
    ret = seteuid(uid);
 
2030
    if(ret == -1){
 
2031
      perror_plus("seteuid");
1760
2032
    }
1761
2033
  }
1762
2034
  
1766
2038
  
1767
2039
  ret = init_gnutls_global(pubkey, seckey);
1768
2040
  if(ret == -1){
1769
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2041
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1770
2042
    exitcode = EX_UNAVAILABLE;
1771
2043
    goto end;
1772
2044
  } else {
1788
2060
  }
1789
2061
  
1790
2062
  if(not init_gpgme(pubkey, seckey, tempdir)){
1791
 
    fprintf(stderr, "init_gpgme failed\n");
 
2063
    fprintf_plus(stderr, "init_gpgme failed\n");
1792
2064
    exitcode = EX_UNAVAILABLE;
1793
2065
    goto end;
1794
2066
  } else {
1804
2076
    /* (Mainly meant for debugging) */
1805
2077
    char *address = strrchr(connect_to, ':');
1806
2078
    if(address == NULL){
1807
 
      fprintf(stderr, "No colon in address\n");
 
2079
      fprintf_plus(stderr, "No colon in address\n");
1808
2080
      exitcode = EX_USAGE;
1809
2081
      goto end;
1810
2082
    }
1818
2090
    tmpmax = strtoimax(address+1, &tmp, 10);
1819
2091
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1820
2092
       or tmpmax != (uint16_t)tmpmax){
1821
 
      fprintf(stderr, "Bad port number\n");
 
2093
      fprintf_plus(stderr, "Bad port number\n");
1822
2094
      exitcode = EX_USAGE;
1823
2095
      goto end;
1824
2096
    }
1829
2101
    
1830
2102
    port = (uint16_t)tmpmax;
1831
2103
    *address = '\0';
1832
 
    address = connect_to;
1833
2104
    /* Colon in address indicates IPv6 */
1834
2105
    int af;
1835
 
    if(strchr(address, ':') != NULL){
 
2106
    if(strchr(connect_to, ':') != NULL){
1836
2107
      af = AF_INET6;
 
2108
      /* Accept [] around IPv6 address - see RFC 5952 */
 
2109
      if(connect_to[0] == '[' and address[-1] == ']')
 
2110
        {
 
2111
          connect_to++;
 
2112
          address[-1] = '\0';
 
2113
        }
1837
2114
    } else {
1838
2115
      af = AF_INET;
1839
2116
    }
 
2117
    address = connect_to;
1840
2118
    
1841
2119
    if(quit_now){
1842
2120
      goto end;
1843
2121
    }
1844
 
 
 
2122
    
1845
2123
    while(not quit_now){
1846
2124
      ret = start_mandos_communication(address, port, if_index, af);
1847
2125
      if(quit_now or ret == 0){
1848
2126
        break;
1849
2127
      }
1850
 
      sleep((int)retry_interval or 1);
1851
 
    };
1852
 
 
 
2128
      if(debug){
 
2129
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2130
                     (int)retry_interval);
 
2131
      }
 
2132
      sleep((int)retry_interval);
 
2133
    }
 
2134
    
1853
2135
    if (not quit_now){
1854
2136
      exitcode = EXIT_SUCCESS;
1855
2137
    }
1856
 
 
 
2138
    
1857
2139
    goto end;
1858
2140
  }
1859
2141
  
1881
2163
  
1882
2164
  /* Check if creating the Avahi server object succeeded */
1883
2165
  if(mc.server == NULL){
1884
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1885
 
            avahi_strerror(error));
 
2166
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2167
                 avahi_strerror(error));
1886
2168
    exitcode = EX_UNAVAILABLE;
1887
2169
    goto end;
1888
2170
  }
1896
2178
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1897
2179
                                   NULL, 0, browse_callback, NULL);
1898
2180
  if(sb == NULL){
1899
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1900
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2181
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2182
                 avahi_strerror(avahi_server_errno(mc.server)));
1901
2183
    exitcode = EX_UNAVAILABLE;
1902
2184
    goto end;
1903
2185
  }
1909
2191
  /* Run the main loop */
1910
2192
  
1911
2193
  if(debug){
1912
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2194
    fprintf_plus(stderr, "Starting Avahi loop search\n");
1913
2195
  }
1914
2196
 
1915
2197
  ret = avahi_loop_with_timeout(mc.simple_poll,
1916
2198
                                (int)(retry_interval * 1000));
1917
2199
  if(debug){
1918
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
1919
 
            (ret == 0) ? "successfully" : "with error");
 
2200
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2201
                 (ret == 0) ? "successfully" : "with error");
1920
2202
  }
1921
2203
  
1922
2204
 end:
1923
2205
  
1924
2206
  if(debug){
1925
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2207
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1926
2208
  }
1927
2209
  
1928
2210
  /* Cleanup things */
1944
2226
  if(gpgme_initialized){
1945
2227
    gpgme_release(mc.ctx);
1946
2228
  }
1947
 
 
 
2229
  
1948
2230
  /* Cleans up the circular linked list of Mandos servers the client
1949
2231
     has seen */
1950
2232
  if(mc.current_server != NULL){
1956
2238
    }
1957
2239
  }
1958
2240
  
1959
 
  /* Take down the network interface */
1960
 
  if(take_down_interface){
1961
 
    /* Re-raise priviliges */
 
2241
  /* Run network hooks */
 
2242
  run_network_hooks("stop", interface, delay);
 
2243
  
 
2244
  /* Re-raise priviliges */
 
2245
  {
1962
2246
    errno = 0;
1963
2247
    ret = seteuid(0);
1964
2248
    if(ret == -1){
1965
2249
      perror_plus("seteuid");
1966
2250
    }
1967
 
    if(geteuid() == 0){
 
2251
    
 
2252
    /* Take down the network interface */
 
2253
    if(take_down_interface and geteuid() == 0){
1968
2254
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1969
2255
      if(ret == -1){
1970
2256
        perror_plus("ioctl SIOCGIFFLAGS");
1971
 
      } else if(network.ifr_flags & IFF_UP) {
 
2257
      } else if(network.ifr_flags & IFF_UP){
1972
2258
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1973
2259
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1974
2260
        if(ret == -1){
1979
2265
      if(ret == -1){
1980
2266
        perror_plus("close");
1981
2267
      }
1982
 
      /* Lower privileges permanently */
1983
 
      errno = 0;
1984
 
      ret = setuid(uid);
1985
 
      if(ret == -1){
1986
 
        perror_plus("setuid");
1987
 
      }
1988
2268
    }
1989
2269
  }
 
2270
  /* Lower privileges permanently */
 
2271
  errno = 0;
 
2272
  ret = setuid(uid);
 
2273
  if(ret == -1){
 
2274
    perror_plus("setuid");
 
2275
  }
1990
2276
  
1991
2277
  /* Removes the GPGME temp directory and all files inside */
1992
2278
  if(tempdir_created){
1993
2279
    struct dirent **direntries = NULL;
1994
2280
    struct dirent *direntry = NULL;
1995
 
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
1996
 
    if (ret > 0){
1997
 
      for(int i = 0; i < ret; i++){
 
2281
    int numentries = scandir(tempdir, &direntries, notdotentries,
 
2282
                             alphasort);
 
2283
    if (numentries > 0){
 
2284
      for(int i = 0; i < numentries; i++){
1998
2285
        direntry = direntries[i];
1999
2286
        char *fullname = NULL;
2000
2287
        ret = asprintf(&fullname, "%s/%s", tempdir,
2005
2292
        }
2006
2293
        ret = remove(fullname);
2007
2294
        if(ret == -1){
2008
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2009
 
                  strerror(errno));
 
2295
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2296
                       strerror(errno));
2010
2297
        }
2011
2298
        free(fullname);
2012
2299
      }
2013
2300
    }
2014
2301
 
2015
 
    /* need to be cleaned even if ret == 0 because man page doesn't
2016
 
       specify */
 
2302
    /* need to clean even if 0 because man page doesn't specify */
2017
2303
    free(direntries);
2018
 
    if (ret == -1){
 
2304
    if (numentries == -1){
2019
2305
      perror_plus("scandir");
2020
2306
    }
2021
2307
    ret = rmdir(tempdir);