/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-03-08 19:09:03 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110308190903-j499ebtb9bpk31ar
* INSTALL: Updated.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
 * "browse_callback", and parts of "main".
10
10
 * 
11
11
 * Everything else is
12
 
 * Copyright © 2008-2012 Teddy Hogeborn
13
 
 * Copyright © 2008-2012 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
58
                                   inet_pton(), connect() */
59
59
#include <fcntl.h>              /* open() */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
64
#include <assert.h>             /* assert() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
 
65
#include <errno.h>              /* perror(), errno */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
75
                                   setgid(), pause() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
85
84
                                   raise() */
86
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
88
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
89
 
                                   WEXITSTATUS(), WTERMSIG() */
90
 
#include <grp.h>                /* setgroups() */
91
87
 
92
88
#ifdef __linux__
93
89
#include <sys/klog.h>           /* klogctl() */
111
107
                                   init_gnutls_session(),
112
108
                                   GNUTLS_* */
113
109
#include <gnutls/openpgp.h>
114
 
                         /* gnutls_certificate_set_openpgp_key_file(),
115
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
110
                          /* gnutls_certificate_set_openpgp_key_file(),
 
111
                                   GNUTLS_OPENPGP_FMT_BASE64 */
116
112
 
117
113
/* GPGME */
118
114
#include <gpgme.h>              /* All GPGME types, constants and
126
122
#define PATHDIR "/conf/conf.d/mandos"
127
123
#define SECKEY "seckey.txt"
128
124
#define PUBKEY "pubkey.txt"
129
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
130
125
 
131
126
bool debug = false;
132
127
static const char mandos_protocol_version[] = "1";
133
128
const char *argp_program_version = "mandos-client " VERSION;
134
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
135
130
static const char sys_class_net[] = "/sys/class/net";
136
131
char *connect_to = NULL;
137
 
const char *hookdir = HOOKDIR;
138
 
 
139
 
/* Doubly linked list that need to be circularly linked when used */
140
 
typedef struct server{
141
 
  const char *ip;
142
 
  uint16_t port;
143
 
  AvahiIfIndex if_index;
144
 
  int af;
145
 
  struct timespec last_seen;
146
 
  struct server *next;
147
 
  struct server *prev;
148
 
} server;
149
132
 
150
133
/* Used for passing in values through the Avahi callback functions */
151
134
typedef struct {
156
139
  gnutls_dh_params_t dh_params;
157
140
  const char *priority;
158
141
  gpgme_ctx_t ctx;
159
 
  server *current_server;
160
142
} mandos_context;
161
143
 
162
144
/* global context so signal handler can reach it*/
163
145
mandos_context mc = { .simple_poll = NULL, .server = NULL,
164
146
                      .dh_bits = 1024, .priority = "SECURE256"
165
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
166
 
                      .current_server = NULL };
 
147
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
167
148
 
168
149
sig_atomic_t quit_now = 0;
169
150
int signal_received = 0;
170
151
 
171
 
/* Function to use when printing errors */
172
 
void perror_plus(const char *print_text){
173
 
  int e = errno;
174
 
  fprintf(stderr, "Mandos plugin %s: ",
175
 
          program_invocation_short_name);
176
 
  errno = e;
177
 
  perror(print_text);
178
 
}
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
 
 
190
152
/*
191
153
 * Make additional room in "buffer" for at least BUFFER_SIZE more
192
154
 * bytes. "buffer_capacity" is how much is currently allocated,
193
155
 * "buffer_length" is how much is already used.
194
156
 */
195
157
size_t incbuffer(char **buffer, size_t buffer_length,
196
 
                 size_t buffer_capacity){
 
158
                  size_t buffer_capacity){
197
159
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
198
160
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
199
161
    if(buffer == NULL){
204
166
  return buffer_capacity;
205
167
}
206
168
 
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){
210
 
  int ret;
211
 
  server *new_server = malloc(sizeof(server));
212
 
  if(new_server == NULL){
213
 
    perror_plus("malloc");
214
 
    return false;
215
 
  }
216
 
  *new_server = (server){ .ip = strdup(ip),
217
 
                          .port = port,
218
 
                          .if_index = if_index,
219
 
                          .af = af };
220
 
  if(new_server->ip == NULL){
221
 
    perror_plus("strdup");
222
 
    return false;
223
 
  }
224
 
  /* Special case of first server */
225
 
  if (mc.current_server == NULL){
226
 
    new_server->next = new_server;
227
 
    new_server->prev = new_server;
228
 
    mc.current_server = new_server;
229
 
  /* Place the new server last in the list */
230
 
  } else {
231
 
    new_server->next = mc.current_server;
232
 
    new_server->prev = mc.current_server->prev;
233
 
    new_server->prev->next = new_server;
234
 
    mc.current_server->prev = new_server;
235
 
  }
236
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
237
 
  if(ret == -1){
238
 
    perror_plus("clock_gettime");
239
 
    return false;
240
 
  }
241
 
  return true;
242
 
}
243
 
 
244
169
/* 
245
170
 * Initialize GPGME.
246
171
 */
247
 
static bool init_gpgme(const char *seckey, const char *pubkey,
248
 
                       const char *tempdir){
 
172
static bool init_gpgme(const char *seckey,
 
173
                       const char *pubkey, const char *tempdir){
249
174
  gpgme_error_t rc;
250
175
  gpgme_engine_info_t engine_info;
251
176
  
260
185
    
261
186
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
262
187
    if(fd == -1){
263
 
      perror_plus("open");
 
188
      perror("open");
264
189
      return false;
265
190
    }
266
191
    
267
192
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
268
193
    if(rc != GPG_ERR_NO_ERROR){
269
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
270
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
194
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
195
              gpgme_strsource(rc), gpgme_strerror(rc));
271
196
      return false;
272
197
    }
273
198
    
274
199
    rc = gpgme_op_import(mc.ctx, pgp_data);
275
200
    if(rc != GPG_ERR_NO_ERROR){
276
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
277
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
201
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
202
              gpgme_strsource(rc), gpgme_strerror(rc));
278
203
      return false;
279
204
    }
280
205
    
281
206
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
282
207
    if(ret == -1){
283
 
      perror_plus("close");
 
208
      perror("close");
284
209
    }
285
210
    gpgme_data_release(pgp_data);
286
211
    return true;
287
212
  }
288
213
  
289
214
  if(debug){
290
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
215
    fprintf(stderr, "Initializing GPGME\n");
291
216
  }
292
217
  
293
218
  /* Init GPGME */
294
219
  gpgme_check_version(NULL);
295
220
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
296
221
  if(rc != GPG_ERR_NO_ERROR){
297
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
298
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
222
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
223
            gpgme_strsource(rc), gpgme_strerror(rc));
299
224
    return false;
300
225
  }
301
226
  
302
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
227
    /* Set GPGME home directory for the OpenPGP engine only */
303
228
  rc = gpgme_get_engine_info(&engine_info);
304
229
  if(rc != GPG_ERR_NO_ERROR){
305
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
306
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
230
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
231
            gpgme_strsource(rc), gpgme_strerror(rc));
307
232
    return false;
308
233
  }
309
234
  while(engine_info != NULL){
315
240
    engine_info = engine_info->next;
316
241
  }
317
242
  if(engine_info == NULL){
318
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
319
 
                 tempdir);
 
243
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
320
244
    return false;
321
245
  }
322
246
  
323
247
  /* Create new GPGME "context" */
324
248
  rc = gpgme_new(&(mc.ctx));
325
249
  if(rc != GPG_ERR_NO_ERROR){
326
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
327
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
328
 
                 gpgme_strerror(rc));
 
250
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
251
            gpgme_strsource(rc), gpgme_strerror(rc));
329
252
    return false;
330
253
  }
331
254
  
350
273
  ssize_t plaintext_length = 0;
351
274
  
352
275
  if(debug){
353
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
276
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
354
277
  }
355
278
  
356
279
  /* Create new GPGME data buffer from memory cryptotext */
357
280
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
358
281
                               0);
359
282
  if(rc != GPG_ERR_NO_ERROR){
360
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
361
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
283
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
284
            gpgme_strsource(rc), gpgme_strerror(rc));
362
285
    return -1;
363
286
  }
364
287
  
365
288
  /* Create new empty GPGME data buffer for the plaintext */
366
289
  rc = gpgme_data_new(&dh_plain);
367
290
  if(rc != GPG_ERR_NO_ERROR){
368
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
369
 
                 "bad gpgme_data_new: %s: %s\n",
370
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
291
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
292
            gpgme_strsource(rc), gpgme_strerror(rc));
371
293
    gpgme_data_release(dh_crypto);
372
294
    return -1;
373
295
  }
376
298
     data buffer */
377
299
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
378
300
  if(rc != GPG_ERR_NO_ERROR){
379
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
380
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
301
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
302
            gpgme_strsource(rc), gpgme_strerror(rc));
381
303
    plaintext_length = -1;
382
304
    if(debug){
383
305
      gpgme_decrypt_result_t result;
384
306
      result = gpgme_op_decrypt_result(mc.ctx);
385
307
      if(result == NULL){
386
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
308
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
387
309
      } else {
388
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
389
 
                     result->unsupported_algorithm);
390
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
391
 
                     result->wrong_key_usage);
 
310
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
311
                result->unsupported_algorithm);
 
312
        fprintf(stderr, "Wrong key usage: %u\n",
 
313
                result->wrong_key_usage);
392
314
        if(result->file_name != NULL){
393
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
315
          fprintf(stderr, "File name: %s\n", result->file_name);
394
316
        }
395
317
        gpgme_recipient_t recipient;
396
318
        recipient = result->recipients;
397
319
        while(recipient != NULL){
398
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
399
 
                       gpgme_pubkey_algo_name
400
 
                       (recipient->pubkey_algo));
401
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
402
 
          fprintf_plus(stderr, "Secret key available: %s\n",
403
 
                       recipient->status == GPG_ERR_NO_SECKEY
404
 
                       ? "No" : "Yes");
 
320
          fprintf(stderr, "Public key algorithm: %s\n",
 
321
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
322
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
323
          fprintf(stderr, "Secret key available: %s\n",
 
324
                  recipient->status == GPG_ERR_NO_SECKEY
 
325
                  ? "No" : "Yes");
405
326
          recipient = recipient->next;
406
327
        }
407
328
      }
410
331
  }
411
332
  
412
333
  if(debug){
413
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
334
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
414
335
  }
415
336
  
416
337
  /* Seek back to the beginning of the GPGME plaintext data buffer */
417
338
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
418
 
    perror_plus("gpgme_data_seek");
 
339
    perror("gpgme_data_seek");
419
340
    plaintext_length = -1;
420
341
    goto decrypt_end;
421
342
  }
423
344
  *plaintext = NULL;
424
345
  while(true){
425
346
    plaintext_capacity = incbuffer(plaintext,
426
 
                                   (size_t)plaintext_length,
427
 
                                   plaintext_capacity);
 
347
                                      (size_t)plaintext_length,
 
348
                                      plaintext_capacity);
428
349
    if(plaintext_capacity == 0){
429
 
      perror_plus("incbuffer");
430
 
      plaintext_length = -1;
431
 
      goto decrypt_end;
 
350
        perror("incbuffer");
 
351
        plaintext_length = -1;
 
352
        goto decrypt_end;
432
353
    }
433
354
    
434
355
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
439
360
      break;
440
361
    }
441
362
    if(ret < 0){
442
 
      perror_plus("gpgme_data_read");
 
363
      perror("gpgme_data_read");
443
364
      plaintext_length = -1;
444
365
      goto decrypt_end;
445
366
    }
447
368
  }
448
369
  
449
370
  if(debug){
450
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
371
    fprintf(stderr, "Decrypted password is: ");
451
372
    for(ssize_t i = 0; i < plaintext_length; i++){
452
373
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
453
374
    }
475
396
/* GnuTLS log function callback */
476
397
static void debuggnutls(__attribute__((unused)) int level,
477
398
                        const char* string){
478
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
399
  fprintf(stderr, "GnuTLS: %s", string);
479
400
}
480
401
 
481
402
static int init_gnutls_global(const char *pubkeyfilename,
483
404
  int ret;
484
405
  
485
406
  if(debug){
486
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
407
    fprintf(stderr, "Initializing GnuTLS\n");
487
408
  }
488
409
  
489
410
  ret = gnutls_global_init();
490
411
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
492
 
                 safer_gnutls_strerror(ret));
 
412
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
413
            safer_gnutls_strerror(ret));
493
414
    return -1;
494
415
  }
495
416
  
502
423
  }
503
424
  
504
425
  /* OpenPGP credentials */
505
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
426
  gnutls_certificate_allocate_credentials(&mc.cred);
506
427
  if(ret != GNUTLS_E_SUCCESS){
507
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
508
 
                 safer_gnutls_strerror(ret));
 
428
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
429
                                                    from
 
430
                                                    -Wunreachable-code
 
431
                                                 */
 
432
            safer_gnutls_strerror(ret));
509
433
    gnutls_global_deinit();
510
434
    return -1;
511
435
  }
512
436
  
513
437
  if(debug){
514
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
515
 
                 " secret key %s as GnuTLS credentials\n",
516
 
                 pubkeyfilename,
517
 
                 seckeyfilename);
 
438
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
439
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
440
            seckeyfilename);
518
441
  }
519
442
  
520
443
  ret = gnutls_certificate_set_openpgp_key_file
521
444
    (mc.cred, pubkeyfilename, seckeyfilename,
522
445
     GNUTLS_OPENPGP_FMT_BASE64);
523
446
  if(ret != GNUTLS_E_SUCCESS){
524
 
    fprintf_plus(stderr,
525
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
526
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
527
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
528
 
                 safer_gnutls_strerror(ret));
 
447
    fprintf(stderr,
 
448
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
449
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
450
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
451
            safer_gnutls_strerror(ret));
529
452
    goto globalfail;
530
453
  }
531
454
  
532
455
  /* GnuTLS server initialization */
533
456
  ret = gnutls_dh_params_init(&mc.dh_params);
534
457
  if(ret != GNUTLS_E_SUCCESS){
535
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
536
 
                 " initialization: %s\n",
537
 
                 safer_gnutls_strerror(ret));
 
458
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
459
            " %s\n", safer_gnutls_strerror(ret));
538
460
    goto globalfail;
539
461
  }
540
462
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
541
463
  if(ret != GNUTLS_E_SUCCESS){
542
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
543
 
                 safer_gnutls_strerror(ret));
 
464
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
465
            safer_gnutls_strerror(ret));
544
466
    goto globalfail;
545
467
  }
546
468
  
566
488
    }
567
489
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
568
490
  if(ret != GNUTLS_E_SUCCESS){
569
 
    fprintf_plus(stderr,
570
 
                 "Error in GnuTLS session initialization: %s\n",
571
 
                 safer_gnutls_strerror(ret));
 
491
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
492
            safer_gnutls_strerror(ret));
572
493
  }
573
494
  
574
495
  {
581
502
      }
582
503
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
583
504
    if(ret != GNUTLS_E_SUCCESS){
584
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
585
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
586
 
                   safer_gnutls_strerror(ret));
 
505
      fprintf(stderr, "Syntax error at: %s\n", err);
 
506
      fprintf(stderr, "GnuTLS error: %s\n",
 
507
              safer_gnutls_strerror(ret));
587
508
      gnutls_deinit(*session);
588
509
      return -1;
589
510
    }
598
519
    }
599
520
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
600
521
  if(ret != GNUTLS_E_SUCCESS){
601
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
602
 
                 safer_gnutls_strerror(ret));
 
522
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
523
            safer_gnutls_strerror(ret));
603
524
    gnutls_deinit(*session);
604
525
    return -1;
605
526
  }
650
571
    pf = PF_INET;
651
572
    break;
652
573
  default:
653
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
574
    fprintf(stderr, "Bad address family: %d\n", af);
654
575
    errno = EINVAL;
655
576
    return -1;
656
577
  }
661
582
  }
662
583
  
663
584
  if(debug){
664
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
665
 
                 PRIu16 "\n", ip, port);
 
585
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
586
            "\n", ip, port);
666
587
  }
667
588
  
668
589
  tcp_sd = socket(pf, SOCK_STREAM, 0);
669
590
  if(tcp_sd < 0){
670
591
    int e = errno;
671
 
    perror_plus("socket");
 
592
    perror("socket");
672
593
    errno = e;
673
594
    goto mandos_end;
674
595
  }
688
609
  }
689
610
  if(ret < 0 ){
690
611
    int e = errno;
691
 
    perror_plus("inet_pton");
 
612
    perror("inet_pton");
692
613
    errno = e;
693
614
    goto mandos_end;
694
615
  }
695
616
  if(ret == 0){
696
617
    int e = errno;
697
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
618
    fprintf(stderr, "Bad address: %s\n", ip);
698
619
    errno = e;
699
620
    goto mandos_end;
700
621
  }
705
626
    
706
627
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
707
628
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
708
 
                                -Wunreachable-code*/
 
629
                              -Wunreachable-code*/
709
630
      if(if_index == AVAHI_IF_UNSPEC){
710
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
711
 
                     " incomplete without a network interface\n");
 
631
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
632
                " without a network interface\n");
712
633
        errno = EINVAL;
713
634
        goto mandos_end;
714
635
      }
730
651
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
731
652
      char interface[IF_NAMESIZE];
732
653
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
733
 
        perror_plus("if_indextoname");
 
654
        perror("if_indextoname");
734
655
      } else {
735
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
736
 
                     "\n", ip, interface, port);
 
656
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
657
                ip, interface, port);
737
658
      }
738
659
    } else {
739
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
740
 
                   ip, port);
 
660
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
661
              port);
741
662
    }
742
663
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
743
664
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
750
671
                        sizeof(addrstr));
751
672
    }
752
673
    if(pcret == NULL){
753
 
      perror_plus("inet_ntop");
 
674
      perror("inet_ntop");
754
675
    } else {
755
676
      if(strcmp(addrstr, ip) != 0){
756
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
677
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
757
678
      }
758
679
    }
759
680
  }
771
692
  if(ret < 0){
772
693
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
773
694
      int e = errno;
774
 
      perror_plus("connect");
 
695
      perror("connect");
775
696
      errno = e;
776
697
    }
777
698
    goto mandos_end;
787
708
  while(true){
788
709
    size_t out_size = strlen(out);
789
710
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
790
 
                                        out_size - written));
 
711
                                   out_size - written));
791
712
    if(ret == -1){
792
713
      int e = errno;
793
 
      perror_plus("write");
 
714
      perror("write");
794
715
      errno = e;
795
716
      goto mandos_end;
796
717
    }
813
734
  }
814
735
  
815
736
  if(debug){
816
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
737
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
817
738
  }
818
739
  
819
740
  if(quit_now){
821
742
    goto mandos_end;
822
743
  }
823
744
  
824
 
  /* Spurious warning from -Wint-to-pointer-cast */
825
745
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
826
746
  
827
747
  if(quit_now){
839
759
  
840
760
  if(ret != GNUTLS_E_SUCCESS){
841
761
    if(debug){
842
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
762
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
843
763
      gnutls_perror(ret);
844
764
    }
845
765
    errno = EPROTO;
849
769
  /* Read OpenPGP packet that contains the wanted password */
850
770
  
851
771
  if(debug){
852
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
853
 
                 " %s\n", ip);
 
772
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
773
            ip);
854
774
  }
855
775
  
856
776
  while(true){
861
781
    }
862
782
    
863
783
    buffer_capacity = incbuffer(&buffer, buffer_length,
864
 
                                buffer_capacity);
 
784
                                   buffer_capacity);
865
785
    if(buffer_capacity == 0){
866
786
      int e = errno;
867
 
      perror_plus("incbuffer");
 
787
      perror("incbuffer");
868
788
      errno = e;
869
789
      goto mandos_end;
870
790
    }
894
814
          }
895
815
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
896
816
        if(ret < 0){
897
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
898
 
                       "***\n");
 
817
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
899
818
          gnutls_perror(ret);
900
819
          errno = EPROTO;
901
820
          goto mandos_end;
902
821
        }
903
822
        break;
904
823
      default:
905
 
        fprintf_plus(stderr, "Unknown error while reading data from"
906
 
                     " encrypted session with Mandos server\n");
 
824
        fprintf(stderr, "Unknown error while reading data from"
 
825
                " encrypted session with Mandos server\n");
907
826
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
908
827
        errno = EIO;
909
828
        goto mandos_end;
914
833
  }
915
834
  
916
835
  if(debug){
917
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
836
    fprintf(stderr, "Closing TLS session\n");
918
837
  }
919
838
  
920
839
  if(quit_now){
932
851
  
933
852
  if(buffer_length > 0){
934
853
    ssize_t decrypted_buffer_size;
935
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
854
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
855
                                               buffer_length,
936
856
                                               &decrypted_buffer);
937
857
    if(decrypted_buffer_size >= 0){
938
858
      
949
869
        if(ret == 0 and ferror(stdout)){
950
870
          int e = errno;
951
871
          if(debug){
952
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
953
 
                         strerror(errno));
 
872
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
873
                    strerror(errno));
954
874
          }
955
875
          errno = e;
956
876
          goto mandos_end;
975
895
      if(e == 0){
976
896
        e = errno;
977
897
      }
978
 
      perror_plus("close");
 
898
      perror("close");
979
899
    }
980
900
    gnutls_deinit(session);
981
 
    errno = e;
982
901
    if(quit_now){
983
 
      errno = EINTR;
 
902
      e = EINTR;
984
903
      retval = -1;
985
904
    }
 
905
    errno = e;
986
906
  }
987
907
  return retval;
988
908
}
1013
933
  switch(event){
1014
934
  default:
1015
935
  case AVAHI_RESOLVER_FAILURE:
1016
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1017
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1018
 
                 domain,
1019
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
936
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
937
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
938
            avahi_strerror(avahi_server_errno(mc.server)));
1020
939
    break;
1021
940
    
1022
941
  case AVAHI_RESOLVER_FOUND:
1024
943
      char ip[AVAHI_ADDRESS_STR_MAX];
1025
944
      avahi_address_snprint(ip, sizeof(ip), address);
1026
945
      if(debug){
1027
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1028
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1029
 
                     host_name, ip, (intmax_t)interface, port);
 
946
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
947
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
948
                ip, (intmax_t)interface, port);
1030
949
      }
1031
950
      int ret = start_mandos_communication(ip, port, interface,
1032
951
                                           avahi_proto_to_af(proto));
1033
952
      if(ret == 0){
1034
953
        avahi_simple_poll_quit(mc.simple_poll);
1035
 
      } else {
1036
 
        if(not add_server(ip, port, interface,
1037
 
                          avahi_proto_to_af(proto))){
1038
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1039
 
                       " list\n", name);
1040
 
        }
1041
954
      }
1042
955
    }
1043
956
  }
1067
980
  default:
1068
981
  case AVAHI_BROWSER_FAILURE:
1069
982
    
1070
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1071
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
983
    fprintf(stderr, "(Avahi browser) %s\n",
 
984
            avahi_strerror(avahi_server_errno(mc.server)));
1072
985
    avahi_simple_poll_quit(mc.simple_poll);
1073
986
    return;
1074
987
    
1081
994
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1082
995
                                    name, type, domain, protocol, 0,
1083
996
                                    resolve_callback, NULL) == NULL)
1084
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1085
 
                   " %s\n", name,
1086
 
                   avahi_strerror(avahi_server_errno(mc.server)));
 
997
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
998
              name, avahi_strerror(avahi_server_errno(mc.server)));
1087
999
    break;
1088
1000
    
1089
1001
  case AVAHI_BROWSER_REMOVE:
1092
1004
  case AVAHI_BROWSER_ALL_FOR_NOW:
1093
1005
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1094
1006
    if(debug){
1095
 
      fprintf_plus(stderr, "No Mandos server found, still"
1096
 
                   " searching...\n");
 
1007
      fprintf(stderr, "No Mandos server found, still searching...\n");
1097
1008
    }
1098
1009
    break;
1099
1010
  }
1100
1011
}
1101
1012
 
1102
 
/* Signal handler that stops main loop after SIGTERM */
 
1013
/* stop main loop after sigterm has been called */
1103
1014
static void handle_sigterm(int sig){
1104
1015
  if(quit_now){
1105
1016
    return;
1107
1018
  quit_now = 1;
1108
1019
  signal_received = sig;
1109
1020
  int old_errno = errno;
1110
 
  /* set main loop to exit */
1111
1021
  if(mc.simple_poll != NULL){
1112
1022
    avahi_simple_poll_quit(mc.simple_poll);
1113
1023
  }
1114
1024
  errno = old_errno;
1115
1025
}
1116
1026
 
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){
 
1027
/* 
 
1028
 * This function determines if a directory entry in /sys/class/net
 
1029
 * corresponds to an acceptable network device.
 
1030
 * (This function is passed to scandir(3) as a filter function.)
 
1031
 */
 
1032
int good_interface(const struct dirent *if_entry){
 
1033
  ssize_t ssret;
 
1034
  char *flagname = NULL;
 
1035
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1036
                     if_entry->d_name);
 
1037
  if(ret < 0){
 
1038
    perror("asprintf");
 
1039
    return 0;
 
1040
  }
 
1041
  if(if_entry->d_name[0] == '.'){
 
1042
    return 0;
 
1043
  }
 
1044
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1045
  if(flags_fd == -1){
 
1046
    perror("open");
 
1047
    return 0;
 
1048
  }
 
1049
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1050
  /* read line from flags_fd */
 
1051
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1052
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1053
  flagstring[(size_t)to_read] = '\0';
 
1054
  if(flagstring == NULL){
 
1055
    perror("malloc");
 
1056
    close(flags_fd);
 
1057
    return 0;
 
1058
  }
 
1059
  while(to_read > 0){
 
1060
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1061
                                             (size_t)to_read));
 
1062
    if(ssret == -1){
 
1063
      perror("read");
 
1064
      free(flagstring);
 
1065
      close(flags_fd);
 
1066
      return 0;
 
1067
    }
 
1068
    to_read -= ssret;
 
1069
    if(ssret == 0){
 
1070
      break;
 
1071
    }
 
1072
  }
 
1073
  close(flags_fd);
 
1074
  intmax_t tmpmax;
 
1075
  char *tmp;
 
1076
  errno = 0;
 
1077
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1078
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1079
                                         and not (isspace(*tmp)))
 
1080
     or tmpmax != (ifreq_flags)tmpmax){
1128
1081
    if(debug){
1129
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1082
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1083
              flagstring, if_entry->d_name);
1130
1084
    }
1131
 
    return false;
 
1085
    free(flagstring);
 
1086
    return 0;
1132
1087
  }
1133
 
  return true;
1134
 
}
1135
 
 
1136
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1137
 
  
 
1088
  free(flagstring);
 
1089
  ifreq_flags flags = (ifreq_flags)tmpmax;
1138
1090
  /* Reject the loopback device */
1139
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1091
  if(flags & IFF_LOOPBACK){
1140
1092
    if(debug){
1141
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1142
 
                   ifname);
 
1093
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1094
              if_entry->d_name);
1143
1095
    }
1144
 
    return false;
 
1096
    return 0;
1145
1097
  }
1146
1098
  /* Accept point-to-point devices only if connect_to is specified */
1147
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1099
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1148
1100
    if(debug){
1149
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1150
 
                   " \"%s\"\n", ifname);
 
1101
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1102
              if_entry->d_name);
1151
1103
    }
1152
 
    return true;
 
1104
    return 1;
1153
1105
  }
1154
1106
  /* Otherwise, reject non-broadcast-capable devices */
1155
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1156
 
    if(debug){
1157
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1158
 
                   " \"%s\"\n", ifname);
1159
 
    }
1160
 
    return false;
1161
 
  }
1162
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1163
 
  if(ifr->ifr_flags & IFF_NOARP){
1164
 
    if(debug){
1165
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1166
 
                   ifname);
1167
 
    }
1168
 
    return false;
1169
 
  }
1170
 
  
 
1107
  if(not (flags & IFF_BROADCAST)){
 
1108
    if(debug){
 
1109
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1110
              if_entry->d_name);
 
1111
    }
 
1112
    return 0;
 
1113
  }
1171
1114
  /* Accept this device */
1172
1115
  if(debug){
1173
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1174
 
  }
1175
 
  return true;
1176
 
}
1177
 
 
1178
 
/* 
1179
 
 * This function determines if a directory entry in /sys/class/net
1180
 
 * corresponds to an acceptable network device.
1181
 
 * (This function is passed to scandir(3) as a filter function.)
1182
 
 */
1183
 
int good_interface(const struct dirent *if_entry){
1184
 
  if(if_entry->d_name[0] == '.'){
1185
 
    return 0;
1186
 
  }
1187
 
  
1188
 
  struct ifreq ifr;
1189
 
  if(not get_flags(if_entry->d_name, &ifr)){
1190
 
    if(debug){
1191
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1192
 
                   "\"%s\"\n", if_entry->d_name);
1193
 
    }
1194
 
    return 0;
1195
 
  }
1196
 
  
1197
 
  if(not good_flags(if_entry->d_name, &ifr)){
1198
 
    return 0;
1199
 
  }
1200
 
  return 1;
1201
 
}
1202
 
 
1203
 
/* 
1204
 
 * This function determines if a directory entry in /sys/class/net
1205
 
 * corresponds to an acceptable network device which is up.
1206
 
 * (This function is passed to scandir(3) as a filter function.)
1207
 
 */
1208
 
int up_interface(const struct dirent *if_entry){
1209
 
  if(if_entry->d_name[0] == '.'){
1210
 
    return 0;
1211
 
  }
1212
 
  
1213
 
  struct ifreq ifr;
1214
 
  if(not get_flags(if_entry->d_name, &ifr)){
1215
 
    if(debug){
1216
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1217
 
                   "\"%s\"\n", if_entry->d_name);
1218
 
    }
1219
 
    return 0;
1220
 
  }
1221
 
  
1222
 
  /* Reject down interfaces */
1223
 
  if(not (ifr.ifr_flags & IFF_UP)){
1224
 
    if(debug){
1225
 
      fprintf_plus(stderr, "Rejecting down interface \"%s\"\n",
1226
 
                   if_entry->d_name);
1227
 
    }
1228
 
    return 0;
1229
 
  }
1230
 
  
1231
 
  /* Reject non-running interfaces */
1232
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1233
 
    if(debug){
1234
 
      fprintf_plus(stderr, "Rejecting non-running interface \"%s\"\n",
1235
 
                   if_entry->d_name);
1236
 
    }
1237
 
    return 0;
1238
 
  }
1239
 
  
1240
 
  if(not good_flags(if_entry->d_name, &ifr)){
1241
 
    return 0;
1242
 
  }
1243
 
  return 1;
1244
 
}
1245
 
 
1246
 
int notdotentries(const struct dirent *direntry){
1247
 
  /* Skip "." and ".." */
1248
 
  if(direntry->d_name[0] == '.'
1249
 
     and (direntry->d_name[1] == '\0'
1250
 
          or (direntry->d_name[1] == '.'
1251
 
              and direntry->d_name[2] == '\0'))){
1252
 
    return 0;
1253
 
  }
1254
 
  return 1;
1255
 
}
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
 
 
1318
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1319
 
  int ret;
1320
 
  struct timespec now;
1321
 
  struct timespec waited_time;
1322
 
  intmax_t block_time;
1323
 
  
1324
 
  while(true){
1325
 
    if(mc.current_server == NULL){
1326
 
      if (debug){
1327
 
        fprintf_plus(stderr, "Wait until first server is found."
1328
 
                     " No timeout!\n");
1329
 
      }
1330
 
      ret = avahi_simple_poll_iterate(s, -1);
1331
 
    } else {
1332
 
      if (debug){
1333
 
        fprintf_plus(stderr, "Check current_server if we should run"
1334
 
                     " it, or wait\n");
1335
 
      }
1336
 
      /* the current time */
1337
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1338
 
      if(ret == -1){
1339
 
        perror_plus("clock_gettime");
1340
 
        return -1;
1341
 
      }
1342
 
      /* Calculating in ms how long time between now and server
1343
 
         who we visted longest time ago. Now - last seen.  */
1344
 
      waited_time.tv_sec = (now.tv_sec
1345
 
                            - mc.current_server->last_seen.tv_sec);
1346
 
      waited_time.tv_nsec = (now.tv_nsec
1347
 
                             - mc.current_server->last_seen.tv_nsec);
1348
 
      /* total time is 10s/10,000ms.
1349
 
         Converting to s from ms by dividing by 1,000,
1350
 
         and ns to ms by dividing by 1,000,000. */
1351
 
      block_time = ((retry_interval
1352
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1353
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1354
 
      
1355
 
      if (debug){
1356
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1357
 
                     block_time);
1358
 
      }
1359
 
      
1360
 
      if(block_time <= 0){
1361
 
        ret = start_mandos_communication(mc.current_server->ip,
1362
 
                                         mc.current_server->port,
1363
 
                                         mc.current_server->if_index,
1364
 
                                         mc.current_server->af);
1365
 
        if(ret == 0){
1366
 
          avahi_simple_poll_quit(mc.simple_poll);
1367
 
          return 0;
1368
 
        }
1369
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1370
 
                            &mc.current_server->last_seen);
1371
 
        if(ret == -1){
1372
 
          perror_plus("clock_gettime");
1373
 
          return -1;
1374
 
        }
1375
 
        mc.current_server = mc.current_server->next;
1376
 
        block_time = 0;         /* Call avahi to find new Mandos
1377
 
                                   servers, but don't block */
1378
 
      }
1379
 
      
1380
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1381
 
    }
1382
 
    if(ret != 0){
1383
 
      if (ret > 0 or errno != EINTR){
1384
 
        return (ret != 1) ? ret : 0;
1385
 
      }
1386
 
    }
1387
 
  }
1388
 
}
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;
 
1116
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1117
            if_entry->d_name);
 
1118
  }
 
1119
  return 1;
1524
1120
}
1525
1121
 
1526
1122
int main(int argc, char *argv[]){
1545
1141
  bool gnutls_initialized = false;
1546
1142
  bool gpgme_initialized = false;
1547
1143
  float delay = 2.5f;
1548
 
  double retry_interval = 10; /* 10s between trying a server and
1549
 
                                 retrying the same server again */
1550
1144
  
1551
1145
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1552
1146
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1558
1152
  errno = 0;
1559
1153
  ret = setgid(gid);
1560
1154
  if(ret == -1){
1561
 
    perror_plus("setgid");
 
1155
    perror("setgid");
1562
1156
  }
1563
1157
  
1564
1158
  /* Lower user privileges (temporarily) */
1565
1159
  errno = 0;
1566
1160
  ret = seteuid(uid);
1567
1161
  if(ret == -1){
1568
 
    perror_plus("seteuid");
 
1162
    perror("seteuid");
1569
1163
  }
1570
1164
  
1571
1165
  if(quit_now){
1606
1200
        .arg = "SECONDS",
1607
1201
        .doc = "Maximum delay to wait for interface startup",
1608
1202
        .group = 2 },
1609
 
      { .name = "retry", .key = 132,
1610
 
        .arg = "SECONDS",
1611
 
        .doc = "Retry interval used when denied by the Mandos server",
1612
 
        .group = 2 },
1613
 
      { .name = "network-hook-dir", .key = 133,
1614
 
        .arg = "DIR",
1615
 
        .doc = "Directory where network hooks are located",
1616
 
        .group = 2 },
1617
1203
      /*
1618
1204
       * These reproduce what we would get without ARGP_NO_HELP
1619
1205
       */
1663
1249
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1664
1250
          argp_error(state, "Bad delay");
1665
1251
        }
1666
 
      case 132:                 /* --retry */
1667
 
        errno = 0;
1668
 
        retry_interval = strtod(arg, &tmp);
1669
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1670
 
           or (retry_interval * 1000) > INT_MAX
1671
 
           or retry_interval < 0){
1672
 
          argp_error(state, "Bad retry interval");
1673
 
        }
1674
 
        break;
1675
 
      case 133:                 /* --network-hook-dir */
1676
 
        hookdir = arg;
1677
1252
        break;
1678
1253
        /*
1679
1254
         * These reproduce what we would get without ARGP_NO_HELP
1686
1261
        argp_state_help(state, state->out_stream,
1687
1262
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1688
1263
      case 'V':                 /* --version */
1689
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1264
        fprintf(state->out_stream, "%s\n", argp_program_version);
1690
1265
        exit(argp_err_exit_status);
1691
1266
        break;
1692
1267
      default:
1707
1282
    case ENOMEM:
1708
1283
    default:
1709
1284
      errno = ret;
1710
 
      perror_plus("argp_parse");
 
1285
      perror("argp_parse");
1711
1286
      exitcode = EX_OSERR;
1712
1287
      goto end;
1713
1288
    case EINVAL:
1715
1290
      goto end;
1716
1291
    }
1717
1292
  }
1718
 
    
1719
 
  {
1720
 
    /* Work around Debian bug #633582:
1721
 
       <http://bugs.debian.org/633582> */
1722
 
    
1723
 
    /* Re-raise priviliges */
1724
 
    errno = 0;
1725
 
    ret = seteuid(0);
1726
 
    if(ret == -1){
1727
 
      perror_plus("seteuid");
1728
 
    } else {
1729
 
      struct stat st;
1730
 
      
1731
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1732
 
        int seckey_fd = open(seckey, O_RDONLY);
1733
 
        if(seckey_fd == -1){
1734
 
          perror_plus("open");
1735
 
        } else {
1736
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1737
 
          if(ret == -1){
1738
 
            perror_plus("fstat");
1739
 
          } else {
1740
 
            if(S_ISREG(st.st_mode)
1741
 
               and st.st_uid == 0 and st.st_gid == 0){
1742
 
              ret = fchown(seckey_fd, uid, gid);
1743
 
              if(ret == -1){
1744
 
                perror_plus("fchown");
1745
 
              }
1746
 
            }
1747
 
          }
1748
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1749
 
        }
1750
 
      }
1751
 
    
1752
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1753
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1754
 
        if(pubkey_fd == -1){
1755
 
          perror_plus("open");
1756
 
        } else {
1757
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1758
 
          if(ret == -1){
1759
 
            perror_plus("fstat");
1760
 
          } else {
1761
 
            if(S_ISREG(st.st_mode)
1762
 
               and st.st_uid == 0 and st.st_gid == 0){
1763
 
              ret = fchown(pubkey_fd, uid, gid);
1764
 
              if(ret == -1){
1765
 
                perror_plus("fchown");
1766
 
              }
1767
 
            }
1768
 
          }
1769
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1770
 
        }
1771
 
      }
1772
 
    
1773
 
      /* Lower privileges */
1774
 
      errno = 0;
1775
 
      ret = seteuid(uid);
1776
 
      if(ret == -1){
1777
 
        perror_plus("seteuid");
1778
 
      }
1779
 
    }
1780
 
  }
1781
 
  
1782
 
  /* Run network hooks */
1783
 
  if(not run_network_hooks("start", interface, delay)){
1784
 
    goto end;
1785
 
  }
1786
1293
  
1787
1294
  if(not debug){
1788
1295
    avahi_set_log_function(empty_log);
1789
1296
  }
1790
 
  
 
1297
 
1791
1298
  if(interface[0] == '\0'){
1792
1299
    struct dirent **direntries;
1793
 
    /* First look for interfaces that are up */
1794
 
    ret = scandir(sys_class_net, &direntries, up_interface,
 
1300
    ret = scandir(sys_class_net, &direntries, good_interface,
1795
1301
                  alphasort);
1796
 
    if(ret == 0){
1797
 
      /* No up interfaces, look for any good interfaces */
1798
 
      free(direntries);
1799
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1800
 
                    alphasort);
1801
 
    }
1802
1302
    if(ret >= 1){
1803
 
      /* Pick the first interface returned */
 
1303
      /* Pick the first good interface */
1804
1304
      interface = strdup(direntries[0]->d_name);
1805
1305
      if(debug){
1806
 
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
 
1306
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1807
1307
      }
1808
1308
      if(interface == NULL){
1809
 
        perror_plus("malloc");
 
1309
        perror("malloc");
1810
1310
        free(direntries);
1811
1311
        exitcode = EXIT_FAILURE;
1812
1312
        goto end;
1814
1314
      free(direntries);
1815
1315
    } else {
1816
1316
      free(direntries);
1817
 
      fprintf_plus(stderr, "Could not find a network interface\n");
 
1317
      fprintf(stderr, "Could not find a network interface\n");
1818
1318
      exitcode = EXIT_FAILURE;
1819
1319
      goto end;
1820
1320
    }
1826
1326
  srand((unsigned int) time(NULL));
1827
1327
  mc.simple_poll = avahi_simple_poll_new();
1828
1328
  if(mc.simple_poll == NULL){
1829
 
    fprintf_plus(stderr,
1830
 
                 "Avahi: Failed to create simple poll object.\n");
 
1329
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
1831
1330
    exitcode = EX_UNAVAILABLE;
1832
1331
    goto end;
1833
1332
  }
1835
1334
  sigemptyset(&sigterm_action.sa_mask);
1836
1335
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1837
1336
  if(ret == -1){
1838
 
    perror_plus("sigaddset");
 
1337
    perror("sigaddset");
1839
1338
    exitcode = EX_OSERR;
1840
1339
    goto end;
1841
1340
  }
1842
1341
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1843
1342
  if(ret == -1){
1844
 
    perror_plus("sigaddset");
 
1343
    perror("sigaddset");
1845
1344
    exitcode = EX_OSERR;
1846
1345
    goto end;
1847
1346
  }
1848
1347
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1849
1348
  if(ret == -1){
1850
 
    perror_plus("sigaddset");
 
1349
    perror("sigaddset");
1851
1350
    exitcode = EX_OSERR;
1852
1351
    goto end;
1853
1352
  }
1857
1356
  */
1858
1357
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1859
1358
  if(ret == -1){
1860
 
    perror_plus("sigaction");
 
1359
    perror("sigaction");
1861
1360
    return EX_OSERR;
1862
1361
  }
1863
1362
  if(old_sigterm_action.sa_handler != SIG_IGN){
1864
1363
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1865
1364
    if(ret == -1){
1866
 
      perror_plus("sigaction");
 
1365
      perror("sigaction");
1867
1366
      exitcode = EX_OSERR;
1868
1367
      goto end;
1869
1368
    }
1870
1369
  }
1871
1370
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1872
1371
  if(ret == -1){
1873
 
    perror_plus("sigaction");
 
1372
    perror("sigaction");
1874
1373
    return EX_OSERR;
1875
1374
  }
1876
1375
  if(old_sigterm_action.sa_handler != SIG_IGN){
1877
1376
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1878
1377
    if(ret == -1){
1879
 
      perror_plus("sigaction");
 
1378
      perror("sigaction");
1880
1379
      exitcode = EX_OSERR;
1881
1380
      goto end;
1882
1381
    }
1883
1382
  }
1884
1383
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1885
1384
  if(ret == -1){
1886
 
    perror_plus("sigaction");
 
1385
    perror("sigaction");
1887
1386
    return EX_OSERR;
1888
1387
  }
1889
1388
  if(old_sigterm_action.sa_handler != SIG_IGN){
1890
1389
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1891
1390
    if(ret == -1){
1892
 
      perror_plus("sigaction");
 
1391
      perror("sigaction");
1893
1392
      exitcode = EX_OSERR;
1894
1393
      goto end;
1895
1394
    }
1899
1398
  if(strcmp(interface, "none") != 0){
1900
1399
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1901
1400
    if(if_index == 0){
1902
 
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1401
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1903
1402
      exitcode = EX_UNAVAILABLE;
1904
1403
      goto end;
1905
1404
    }
1912
1411
    errno = 0;
1913
1412
    ret = seteuid(0);
1914
1413
    if(ret == -1){
1915
 
      perror_plus("seteuid");
 
1414
      perror("seteuid");
1916
1415
    }
1917
1416
    
1918
1417
#ifdef __linux__
1922
1421
    bool restore_loglevel = true;
1923
1422
    if(ret == -1){
1924
1423
      restore_loglevel = false;
1925
 
      perror_plus("klogctl");
 
1424
      perror("klogctl");
1926
1425
    }
1927
1426
#endif  /* __linux__ */
1928
1427
    
1929
1428
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1930
1429
    if(sd < 0){
1931
 
      perror_plus("socket");
 
1430
      perror("socket");
1932
1431
      exitcode = EX_OSERR;
1933
1432
#ifdef __linux__
1934
1433
      if(restore_loglevel){
1935
1434
        ret = klogctl(7, NULL, 0);
1936
1435
        if(ret == -1){
1937
 
          perror_plus("klogctl");
 
1436
          perror("klogctl");
1938
1437
        }
1939
1438
      }
1940
1439
#endif  /* __linux__ */
1942
1441
      errno = 0;
1943
1442
      ret = seteuid(uid);
1944
1443
      if(ret == -1){
1945
 
        perror_plus("seteuid");
 
1444
        perror("seteuid");
1946
1445
      }
1947
1446
      goto end;
1948
1447
    }
1949
1448
    strcpy(network.ifr_name, interface);
1950
1449
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1951
1450
    if(ret == -1){
1952
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1451
      perror("ioctl SIOCGIFFLAGS");
1953
1452
#ifdef __linux__
1954
1453
      if(restore_loglevel){
1955
1454
        ret = klogctl(7, NULL, 0);
1956
1455
        if(ret == -1){
1957
 
          perror_plus("klogctl");
 
1456
          perror("klogctl");
1958
1457
        }
1959
1458
      }
1960
1459
#endif  /* __linux__ */
1963
1462
      errno = 0;
1964
1463
      ret = seteuid(uid);
1965
1464
      if(ret == -1){
1966
 
        perror_plus("seteuid");
 
1465
        perror("seteuid");
1967
1466
      }
1968
1467
      goto end;
1969
1468
    }
1973
1472
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1974
1473
      if(ret == -1){
1975
1474
        take_down_interface = false;
1976
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1475
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
1977
1476
        exitcode = EX_OSERR;
1978
1477
#ifdef __linux__
1979
1478
        if(restore_loglevel){
1980
1479
          ret = klogctl(7, NULL, 0);
1981
1480
          if(ret == -1){
1982
 
            perror_plus("klogctl");
 
1481
            perror("klogctl");
1983
1482
          }
1984
1483
        }
1985
1484
#endif  /* __linux__ */
1987
1486
        errno = 0;
1988
1487
        ret = seteuid(uid);
1989
1488
        if(ret == -1){
1990
 
          perror_plus("seteuid");
 
1489
          perror("seteuid");
1991
1490
        }
1992
1491
        goto end;
1993
1492
      }
1994
1493
    }
1995
 
    /* Sleep checking until interface is running.
1996
 
       Check every 0.25s, up to total time of delay */
 
1494
    /* sleep checking until interface is running */
1997
1495
    for(int i=0; i < delay * 4; i++){
1998
1496
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1999
1497
      if(ret == -1){
2000
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1498
        perror("ioctl SIOCGIFFLAGS");
2001
1499
      } else if(network.ifr_flags & IFF_RUNNING){
2002
1500
        break;
2003
1501
      }
2004
1502
      struct timespec sleeptime = { .tv_nsec = 250000000 };
2005
1503
      ret = nanosleep(&sleeptime, NULL);
2006
1504
      if(ret == -1 and errno != EINTR){
2007
 
        perror_plus("nanosleep");
 
1505
        perror("nanosleep");
2008
1506
      }
2009
1507
    }
2010
1508
    if(not take_down_interface){
2011
1509
      /* We won't need the socket anymore */
2012
1510
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2013
1511
      if(ret == -1){
2014
 
        perror_plus("close");
 
1512
        perror("close");
2015
1513
      }
2016
1514
    }
2017
1515
#ifdef __linux__
2019
1517
      /* Restores kernel loglevel to default */
2020
1518
      ret = klogctl(7, NULL, 0);
2021
1519
      if(ret == -1){
2022
 
        perror_plus("klogctl");
 
1520
        perror("klogctl");
2023
1521
      }
2024
1522
    }
2025
1523
#endif  /* __linux__ */
2026
1524
    /* Lower privileges */
2027
1525
    errno = 0;
2028
 
    /* Lower privileges */
2029
 
    ret = seteuid(uid);
2030
 
    if(ret == -1){
2031
 
      perror_plus("seteuid");
 
1526
    if(take_down_interface){
 
1527
      /* Lower privileges */
 
1528
      ret = seteuid(uid);
 
1529
      if(ret == -1){
 
1530
        perror("seteuid");
 
1531
      }
 
1532
    } else {
 
1533
      /* Lower privileges permanently */
 
1534
      ret = setuid(uid);
 
1535
      if(ret == -1){
 
1536
        perror("setuid");
 
1537
      }
2032
1538
    }
2033
1539
  }
2034
1540
  
2038
1544
  
2039
1545
  ret = init_gnutls_global(pubkey, seckey);
2040
1546
  if(ret == -1){
2041
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1547
    fprintf(stderr, "init_gnutls_global failed\n");
2042
1548
    exitcode = EX_UNAVAILABLE;
2043
1549
    goto end;
2044
1550
  } else {
2049
1555
    goto end;
2050
1556
  }
2051
1557
  
 
1558
  tempdir_created = true;
2052
1559
  if(mkdtemp(tempdir) == NULL){
2053
 
    perror_plus("mkdtemp");
 
1560
    tempdir_created = false;
 
1561
    perror("mkdtemp");
2054
1562
    goto end;
2055
1563
  }
2056
 
  tempdir_created = true;
2057
1564
  
2058
1565
  if(quit_now){
2059
1566
    goto end;
2060
1567
  }
2061
1568
  
2062
1569
  if(not init_gpgme(pubkey, seckey, tempdir)){
2063
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1570
    fprintf(stderr, "init_gpgme failed\n");
2064
1571
    exitcode = EX_UNAVAILABLE;
2065
1572
    goto end;
2066
1573
  } else {
2076
1583
    /* (Mainly meant for debugging) */
2077
1584
    char *address = strrchr(connect_to, ':');
2078
1585
    if(address == NULL){
2079
 
      fprintf_plus(stderr, "No colon in address\n");
 
1586
      fprintf(stderr, "No colon in address\n");
2080
1587
      exitcode = EX_USAGE;
2081
1588
      goto end;
2082
1589
    }
2090
1597
    tmpmax = strtoimax(address+1, &tmp, 10);
2091
1598
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2092
1599
       or tmpmax != (uint16_t)tmpmax){
2093
 
      fprintf_plus(stderr, "Bad port number\n");
 
1600
      fprintf(stderr, "Bad port number\n");
2094
1601
      exitcode = EX_USAGE;
2095
1602
      goto end;
2096
1603
    }
2101
1608
    
2102
1609
    port = (uint16_t)tmpmax;
2103
1610
    *address = '\0';
 
1611
    address = connect_to;
2104
1612
    /* Colon in address indicates IPv6 */
2105
1613
    int af;
2106
 
    if(strchr(connect_to, ':') != NULL){
 
1614
    if(strchr(address, ':') != NULL){
2107
1615
      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
 
        }
2114
1616
    } else {
2115
1617
      af = AF_INET;
2116
1618
    }
2117
 
    address = connect_to;
2118
1619
    
2119
1620
    if(quit_now){
2120
1621
      goto end;
2121
1622
    }
2122
 
    
 
1623
 
2123
1624
    while(not quit_now){
2124
1625
      ret = start_mandos_communication(address, port, if_index, af);
2125
1626
      if(quit_now or ret == 0){
2126
1627
        break;
2127
1628
      }
2128
 
      if(debug){
2129
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2130
 
                     (int)retry_interval);
2131
 
      }
2132
 
      sleep((int)retry_interval);
2133
 
    }
2134
 
    
 
1629
      sleep(15);
 
1630
    };
 
1631
 
2135
1632
    if (not quit_now){
2136
1633
      exitcode = EXIT_SUCCESS;
2137
1634
    }
2138
 
    
 
1635
 
2139
1636
    goto end;
2140
1637
  }
2141
1638
  
2163
1660
  
2164
1661
  /* Check if creating the Avahi server object succeeded */
2165
1662
  if(mc.server == NULL){
2166
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2167
 
                 avahi_strerror(error));
 
1663
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1664
            avahi_strerror(error));
2168
1665
    exitcode = EX_UNAVAILABLE;
2169
1666
    goto end;
2170
1667
  }
2178
1675
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2179
1676
                                   NULL, 0, browse_callback, NULL);
2180
1677
  if(sb == NULL){
2181
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2182
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1678
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1679
            avahi_strerror(avahi_server_errno(mc.server)));
2183
1680
    exitcode = EX_UNAVAILABLE;
2184
1681
    goto end;
2185
1682
  }
2191
1688
  /* Run the main loop */
2192
1689
  
2193
1690
  if(debug){
2194
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2195
 
  }
2196
 
 
2197
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2198
 
                                (int)(retry_interval * 1000));
2199
 
  if(debug){
2200
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2201
 
                 (ret == 0) ? "successfully" : "with error");
2202
 
  }
 
1691
    fprintf(stderr, "Starting Avahi loop search\n");
 
1692
  }
 
1693
  
 
1694
  avahi_simple_poll_loop(mc.simple_poll);
2203
1695
  
2204
1696
 end:
2205
1697
  
2206
1698
  if(debug){
2207
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1699
    fprintf(stderr, "%s exiting\n", argv[0]);
2208
1700
  }
2209
1701
  
2210
1702
  /* Cleanup things */
2227
1719
    gpgme_release(mc.ctx);
2228
1720
  }
2229
1721
  
2230
 
  /* Cleans up the circular linked list of Mandos servers the client
2231
 
     has seen */
2232
 
  if(mc.current_server != NULL){
2233
 
    mc.current_server->prev->next = NULL;
2234
 
    while(mc.current_server != NULL){
2235
 
      server *next = mc.current_server->next;
2236
 
      free(mc.current_server);
2237
 
      mc.current_server = next;
2238
 
    }
2239
 
  }
2240
 
  
2241
 
  /* Run network hooks */
2242
 
  run_network_hooks("stop", interface, delay);
2243
 
  
2244
 
  /* Re-raise priviliges */
2245
 
  {
 
1722
  /* Take down the network interface */
 
1723
  if(take_down_interface){
 
1724
    /* Re-raise priviliges */
2246
1725
    errno = 0;
2247
1726
    ret = seteuid(0);
2248
1727
    if(ret == -1){
2249
 
      perror_plus("seteuid");
 
1728
      perror("seteuid");
2250
1729
    }
2251
 
    
2252
 
    /* Take down the network interface */
2253
 
    if(take_down_interface and geteuid() == 0){
 
1730
    if(geteuid() == 0){
2254
1731
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2255
1732
      if(ret == -1){
2256
 
        perror_plus("ioctl SIOCGIFFLAGS");
2257
 
      } else if(network.ifr_flags & IFF_UP){
 
1733
        perror("ioctl SIOCGIFFLAGS");
 
1734
      } else if(network.ifr_flags & IFF_UP) {
2258
1735
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2259
1736
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2260
1737
        if(ret == -1){
2261
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1738
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
2262
1739
        }
2263
1740
      }
2264
1741
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2265
1742
      if(ret == -1){
2266
 
        perror_plus("close");
 
1743
        perror("close");
 
1744
      }
 
1745
      /* Lower privileges permanently */
 
1746
      errno = 0;
 
1747
      ret = setuid(uid);
 
1748
      if(ret == -1){
 
1749
        perror("setuid");
2267
1750
      }
2268
1751
    }
2269
1752
  }
2270
 
  /* Lower privileges permanently */
2271
 
  errno = 0;
2272
 
  ret = setuid(uid);
2273
 
  if(ret == -1){
2274
 
    perror_plus("setuid");
2275
 
  }
2276
1753
  
2277
 
  /* Removes the GPGME temp directory and all files inside */
 
1754
  /* Removes the temp directory used by GPGME */
2278
1755
  if(tempdir_created){
2279
 
    struct dirent **direntries = NULL;
2280
 
    struct dirent *direntry = NULL;
2281
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2282
 
                             alphasort);
2283
 
    if (numentries > 0){
2284
 
      for(int i = 0; i < numentries; i++){
2285
 
        direntry = direntries[i];
 
1756
    DIR *d;
 
1757
    struct dirent *direntry;
 
1758
    d = opendir(tempdir);
 
1759
    if(d == NULL){
 
1760
      if(errno != ENOENT){
 
1761
        perror("opendir");
 
1762
      }
 
1763
    } else {
 
1764
      while(true){
 
1765
        direntry = readdir(d);
 
1766
        if(direntry == NULL){
 
1767
          break;
 
1768
        }
 
1769
        /* Skip "." and ".." */
 
1770
        if(direntry->d_name[0] == '.'
 
1771
           and (direntry->d_name[1] == '\0'
 
1772
                or (direntry->d_name[1] == '.'
 
1773
                    and direntry->d_name[2] == '\0'))){
 
1774
          continue;
 
1775
        }
2286
1776
        char *fullname = NULL;
2287
1777
        ret = asprintf(&fullname, "%s/%s", tempdir,
2288
1778
                       direntry->d_name);
2289
1779
        if(ret < 0){
2290
 
          perror_plus("asprintf");
 
1780
          perror("asprintf");
2291
1781
          continue;
2292
1782
        }
2293
1783
        ret = remove(fullname);
2294
1784
        if(ret == -1){
2295
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2296
 
                       strerror(errno));
 
1785
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1786
                  strerror(errno));
2297
1787
        }
2298
1788
        free(fullname);
2299
1789
      }
2300
 
    }
2301
 
 
2302
 
    /* need to clean even if 0 because man page doesn't specify */
2303
 
    free(direntries);
2304
 
    if (numentries == -1){
2305
 
      perror_plus("scandir");
 
1790
      closedir(d);
2306
1791
    }
2307
1792
    ret = rmdir(tempdir);
2308
1793
    if(ret == -1 and errno != ENOENT){
2309
 
      perror_plus("rmdir");
 
1794
      perror("rmdir");
2310
1795
    }
2311
1796
  }
2312
1797
  
2317
1802
                                            &old_sigterm_action,
2318
1803
                                            NULL));
2319
1804
    if(ret == -1){
2320
 
      perror_plus("sigaction");
 
1805
      perror("sigaction");
2321
1806
    }
2322
1807
    do {
2323
1808
      ret = raise(signal_received);
2324
1809
    } while(ret != 0 and errno == EINTR);
2325
1810
    if(ret != 0){
2326
 
      perror_plus("raise");
 
1811
      perror("raise");
2327
1812
      abort();
2328
1813
    }
2329
1814
    TEMP_FAILURE_RETRY(pause());