/mandos/release

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

« back to all changes in this revision

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

* network-hooks.d: New directory.
* network-hooks.d/bridge: New example hook.
* network-hooks.d/bridge.conf: Config file for bridge example hook.

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