/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

  • Committer: Teddy Hogeborn
  • Date: 2011-03-08 19:41:59 UTC
  • Revision ID: teddy@fukt.bsnet.se-20110308194159-h0p66a3rabn8cjkb
Tags: version-1.3.0-1
* Makefile (version): Changed to "1.3.0".
* NEWS (Version 1.3.0): New entry.
* debian/changelog (1.3.0-1): - '' -

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() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
43
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
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() */
61
61
                                 */
62
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
63
                                   strtoimax() */
64
 
#include <errno.h>              /* perror(), errno,
65
 
                                   program_invocation_short_name */
 
64
#include <assert.h>             /* assert() */
 
65
#include <errno.h>              /* perror(), errno */
66
66
#include <time.h>               /* nanosleep(), time(), sleep() */
67
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
68
                                   SIOCSIFFLAGS, if_indextoname(),
72
72
                                */
73
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
74
74
                                   getuid(), getgid(), seteuid(),
75
 
                                   setgid(), pause(), _exit() */
76
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
75
                                   setgid(), pause() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
77
77
#include <iso646.h>             /* not, or, and */
78
78
#include <argp.h>               /* struct argp_option, error_t, struct
79
79
                                   argp_state, struct argp,
84
84
                                   raise() */
85
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
86
86
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
87
 
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
88
 
                                   WEXITSTATUS(), WTERMSIG() */
89
 
#include <grp.h>                /* setgroups() */
90
 
#include <argz.h>               /* argz_add_sep(), argz_next(),
91
 
                                   argz_delete(), argz_append(),
92
 
                                   argz_stringify(), argz_add(),
93
 
                                   argz_count() */
94
87
 
95
88
#ifdef __linux__
96
89
#include <sys/klog.h>           /* klogctl() */
114
107
                                   init_gnutls_session(),
115
108
                                   GNUTLS_* */
116
109
#include <gnutls/openpgp.h>
117
 
                         /* gnutls_certificate_set_openpgp_key_file(),
118
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
110
                          /* gnutls_certificate_set_openpgp_key_file(),
 
111
                                   GNUTLS_OPENPGP_FMT_BASE64 */
119
112
 
120
113
/* GPGME */
121
114
#include <gpgme.h>              /* All GPGME types, constants and
129
122
#define PATHDIR "/conf/conf.d/mandos"
130
123
#define SECKEY "seckey.txt"
131
124
#define PUBKEY "pubkey.txt"
132
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
133
125
 
134
126
bool debug = false;
135
127
static const char mandos_protocol_version[] = "1";
136
128
const char *argp_program_version = "mandos-client " VERSION;
137
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
138
130
static const char sys_class_net[] = "/sys/class/net";
139
131
char *connect_to = NULL;
140
 
const char *hookdir = HOOKDIR;
141
 
uid_t uid = 65534;
142
 
gid_t gid = 65534;
143
 
 
144
 
/* Doubly linked list that need to be circularly linked when used */
145
 
typedef struct server{
146
 
  const char *ip;
147
 
  in_port_t port;
148
 
  AvahiIfIndex if_index;
149
 
  int af;
150
 
  struct timespec last_seen;
151
 
  struct server *next;
152
 
  struct server *prev;
153
 
} server;
154
132
 
155
133
/* Used for passing in values through the Avahi callback functions */
156
134
typedef struct {
 
135
  AvahiSimplePoll *simple_poll;
157
136
  AvahiServer *server;
158
137
  gnutls_certificate_credentials_t cred;
159
138
  unsigned int dh_bits;
160
139
  gnutls_dh_params_t dh_params;
161
140
  const char *priority;
162
141
  gpgme_ctx_t ctx;
163
 
  server *current_server;
164
142
} mandos_context;
165
143
 
166
 
/* global so signal handler can reach it*/
167
 
AvahiSimplePoll *simple_poll;
168
 
mandos_context mc = { .server = NULL, .dh_bits = 1024,
169
 
                      .priority = "SECURE256:!CTYPE-X.509:"
170
 
                      "+CTYPE-OPENPGP", .current_server = NULL };
 
144
/* global context so signal handler can reach it*/
 
145
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
146
                      .dh_bits = 1024, .priority = "SECURE256"
 
147
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
171
148
 
172
149
sig_atomic_t quit_now = 0;
173
150
int signal_received = 0;
174
151
 
175
 
/* Function to use when printing errors */
176
 
void perror_plus(const char *print_text){
177
 
  int e = errno;
178
 
  fprintf(stderr, "Mandos plugin %s: ",
179
 
          program_invocation_short_name);
180
 
  errno = e;
181
 
  perror(print_text);
182
 
}
183
 
 
184
 
__attribute__((format (gnu_printf, 2, 3)))
185
 
int fprintf_plus(FILE *stream, const char *format, ...){
186
 
  va_list ap;
187
 
  va_start (ap, format);
188
 
  
189
 
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
190
 
                             program_invocation_short_name));
191
 
  return TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
192
 
}
193
 
 
194
152
/*
195
153
 * Make additional room in "buffer" for at least BUFFER_SIZE more
196
154
 * bytes. "buffer_capacity" is how much is currently allocated,
197
155
 * "buffer_length" is how much is already used.
198
156
 */
199
157
size_t incbuffer(char **buffer, size_t buffer_length,
200
 
                 size_t buffer_capacity){
 
158
                  size_t buffer_capacity){
201
159
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
202
160
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
203
161
    if(buffer == NULL){
208
166
  return buffer_capacity;
209
167
}
210
168
 
211
 
/* Add server to set of servers to retry periodically */
212
 
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
213
 
                int af){
214
 
  int ret;
215
 
  server *new_server = malloc(sizeof(server));
216
 
  if(new_server == NULL){
217
 
    perror_plus("malloc");
218
 
    return false;
219
 
  }
220
 
  *new_server = (server){ .ip = strdup(ip),
221
 
                          .port = port,
222
 
                          .if_index = if_index,
223
 
                          .af = af };
224
 
  if(new_server->ip == NULL){
225
 
    perror_plus("strdup");
226
 
    return false;
227
 
  }
228
 
  /* Special case of first server */
229
 
  if (mc.current_server == NULL){
230
 
    new_server->next = new_server;
231
 
    new_server->prev = new_server;
232
 
    mc.current_server = new_server;
233
 
  /* Place the new server last in the list */
234
 
  } else {
235
 
    new_server->next = mc.current_server;
236
 
    new_server->prev = mc.current_server->prev;
237
 
    new_server->prev->next = new_server;
238
 
    mc.current_server->prev = new_server;
239
 
  }
240
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
241
 
  if(ret == -1){
242
 
    perror_plus("clock_gettime");
243
 
    return false;
244
 
  }
245
 
  return true;
246
 
}
247
 
 
248
169
/* 
249
170
 * Initialize GPGME.
250
171
 */
251
 
static bool init_gpgme(const char *seckey, const char *pubkey,
252
 
                       const char *tempdir){
 
172
static bool init_gpgme(const char *seckey,
 
173
                       const char *pubkey, const char *tempdir){
253
174
  gpgme_error_t rc;
254
175
  gpgme_engine_info_t engine_info;
255
176
  
 
177
  
256
178
  /*
257
179
   * Helper function to insert pub and seckey to the engine keyring.
258
180
   */
263
185
    
264
186
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
265
187
    if(fd == -1){
266
 
      perror_plus("open");
 
188
      perror("open");
267
189
      return false;
268
190
    }
269
191
    
270
192
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
271
193
    if(rc != GPG_ERR_NO_ERROR){
272
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
273
 
                   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));
274
196
      return false;
275
197
    }
276
198
    
277
199
    rc = gpgme_op_import(mc.ctx, pgp_data);
278
200
    if(rc != GPG_ERR_NO_ERROR){
279
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
280
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
201
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
202
              gpgme_strsource(rc), gpgme_strerror(rc));
281
203
      return false;
282
204
    }
283
205
    
284
206
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
285
207
    if(ret == -1){
286
 
      perror_plus("close");
 
208
      perror("close");
287
209
    }
288
210
    gpgme_data_release(pgp_data);
289
211
    return true;
290
212
  }
291
213
  
292
214
  if(debug){
293
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
215
    fprintf(stderr, "Initializing GPGME\n");
294
216
  }
295
217
  
296
218
  /* Init GPGME */
297
219
  gpgme_check_version(NULL);
298
220
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
299
221
  if(rc != GPG_ERR_NO_ERROR){
300
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
301
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
222
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
223
            gpgme_strsource(rc), gpgme_strerror(rc));
302
224
    return false;
303
225
  }
304
226
  
305
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
227
    /* Set GPGME home directory for the OpenPGP engine only */
306
228
  rc = gpgme_get_engine_info(&engine_info);
307
229
  if(rc != GPG_ERR_NO_ERROR){
308
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
309
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
230
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
231
            gpgme_strsource(rc), gpgme_strerror(rc));
310
232
    return false;
311
233
  }
312
234
  while(engine_info != NULL){
318
240
    engine_info = engine_info->next;
319
241
  }
320
242
  if(engine_info == NULL){
321
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
322
 
                 tempdir);
 
243
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
323
244
    return false;
324
245
  }
325
246
  
326
247
  /* Create new GPGME "context" */
327
248
  rc = gpgme_new(&(mc.ctx));
328
249
  if(rc != GPG_ERR_NO_ERROR){
329
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
330
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
331
 
                 gpgme_strerror(rc));
 
250
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
251
            gpgme_strsource(rc), gpgme_strerror(rc));
332
252
    return false;
333
253
  }
334
254
  
353
273
  ssize_t plaintext_length = 0;
354
274
  
355
275
  if(debug){
356
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
276
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
357
277
  }
358
278
  
359
279
  /* Create new GPGME data buffer from memory cryptotext */
360
280
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
361
281
                               0);
362
282
  if(rc != GPG_ERR_NO_ERROR){
363
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
364
 
                 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));
365
285
    return -1;
366
286
  }
367
287
  
368
288
  /* Create new empty GPGME data buffer for the plaintext */
369
289
  rc = gpgme_data_new(&dh_plain);
370
290
  if(rc != GPG_ERR_NO_ERROR){
371
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
372
 
                 "bad gpgme_data_new: %s: %s\n",
373
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
291
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
292
            gpgme_strsource(rc), gpgme_strerror(rc));
374
293
    gpgme_data_release(dh_crypto);
375
294
    return -1;
376
295
  }
379
298
     data buffer */
380
299
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
381
300
  if(rc != GPG_ERR_NO_ERROR){
382
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
383
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
301
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
302
            gpgme_strsource(rc), gpgme_strerror(rc));
384
303
    plaintext_length = -1;
385
304
    if(debug){
386
305
      gpgme_decrypt_result_t result;
387
306
      result = gpgme_op_decrypt_result(mc.ctx);
388
307
      if(result == NULL){
389
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
308
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
390
309
      } else {
391
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
392
 
                     result->unsupported_algorithm);
393
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
394
 
                     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);
395
314
        if(result->file_name != NULL){
396
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
315
          fprintf(stderr, "File name: %s\n", result->file_name);
397
316
        }
398
317
        gpgme_recipient_t recipient;
399
318
        recipient = result->recipients;
400
319
        while(recipient != NULL){
401
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
402
 
                       gpgme_pubkey_algo_name
403
 
                       (recipient->pubkey_algo));
404
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
405
 
          fprintf_plus(stderr, "Secret key available: %s\n",
406
 
                       recipient->status == GPG_ERR_NO_SECKEY
407
 
                       ? "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");
408
326
          recipient = recipient->next;
409
327
        }
410
328
      }
413
331
  }
414
332
  
415
333
  if(debug){
416
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
334
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
417
335
  }
418
336
  
419
337
  /* Seek back to the beginning of the GPGME plaintext data buffer */
420
338
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
421
 
    perror_plus("gpgme_data_seek");
 
339
    perror("gpgme_data_seek");
422
340
    plaintext_length = -1;
423
341
    goto decrypt_end;
424
342
  }
426
344
  *plaintext = NULL;
427
345
  while(true){
428
346
    plaintext_capacity = incbuffer(plaintext,
429
 
                                   (size_t)plaintext_length,
430
 
                                   plaintext_capacity);
 
347
                                      (size_t)plaintext_length,
 
348
                                      plaintext_capacity);
431
349
    if(plaintext_capacity == 0){
432
 
      perror_plus("incbuffer");
433
 
      plaintext_length = -1;
434
 
      goto decrypt_end;
 
350
        perror("incbuffer");
 
351
        plaintext_length = -1;
 
352
        goto decrypt_end;
435
353
    }
436
354
    
437
355
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
442
360
      break;
443
361
    }
444
362
    if(ret < 0){
445
 
      perror_plus("gpgme_data_read");
 
363
      perror("gpgme_data_read");
446
364
      plaintext_length = -1;
447
365
      goto decrypt_end;
448
366
    }
450
368
  }
451
369
  
452
370
  if(debug){
453
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
371
    fprintf(stderr, "Decrypted password is: ");
454
372
    for(ssize_t i = 0; i < plaintext_length; i++){
455
373
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
456
374
    }
468
386
}
469
387
 
470
388
static const char * safer_gnutls_strerror(int value){
471
 
  const char *ret = gnutls_strerror(value);
 
389
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
390
                                               -Wunreachable-code */
472
391
  if(ret == NULL)
473
392
    ret = "(unknown)";
474
393
  return ret;
477
396
/* GnuTLS log function callback */
478
397
static void debuggnutls(__attribute__((unused)) int level,
479
398
                        const char* string){
480
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
399
  fprintf(stderr, "GnuTLS: %s", string);
481
400
}
482
401
 
483
402
static int init_gnutls_global(const char *pubkeyfilename,
485
404
  int ret;
486
405
  
487
406
  if(debug){
488
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
407
    fprintf(stderr, "Initializing GnuTLS\n");
489
408
  }
490
409
  
491
410
  ret = gnutls_global_init();
492
411
  if(ret != GNUTLS_E_SUCCESS){
493
 
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
494
 
                 safer_gnutls_strerror(ret));
 
412
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
413
            safer_gnutls_strerror(ret));
495
414
    return -1;
496
415
  }
497
416
  
504
423
  }
505
424
  
506
425
  /* OpenPGP credentials */
507
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
426
  gnutls_certificate_allocate_credentials(&mc.cred);
508
427
  if(ret != GNUTLS_E_SUCCESS){
509
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
510
 
                 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));
511
433
    gnutls_global_deinit();
512
434
    return -1;
513
435
  }
514
436
  
515
437
  if(debug){
516
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
517
 
                 " secret key %s as GnuTLS credentials\n",
518
 
                 pubkeyfilename,
519
 
                 seckeyfilename);
 
438
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
439
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
440
            seckeyfilename);
520
441
  }
521
442
  
522
443
  ret = gnutls_certificate_set_openpgp_key_file
523
444
    (mc.cred, pubkeyfilename, seckeyfilename,
524
445
     GNUTLS_OPENPGP_FMT_BASE64);
525
446
  if(ret != GNUTLS_E_SUCCESS){
526
 
    fprintf_plus(stderr,
527
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
528
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
529
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
530
 
                 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));
531
452
    goto globalfail;
532
453
  }
533
454
  
534
455
  /* GnuTLS server initialization */
535
456
  ret = gnutls_dh_params_init(&mc.dh_params);
536
457
  if(ret != GNUTLS_E_SUCCESS){
537
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
538
 
                 " initialization: %s\n",
539
 
                 safer_gnutls_strerror(ret));
 
458
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
459
            " %s\n", safer_gnutls_strerror(ret));
540
460
    goto globalfail;
541
461
  }
542
462
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
543
463
  if(ret != GNUTLS_E_SUCCESS){
544
 
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
545
 
                 safer_gnutls_strerror(ret));
 
464
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
465
            safer_gnutls_strerror(ret));
546
466
    goto globalfail;
547
467
  }
548
468
  
568
488
    }
569
489
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
570
490
  if(ret != GNUTLS_E_SUCCESS){
571
 
    fprintf_plus(stderr,
572
 
                 "Error in GnuTLS session initialization: %s\n",
573
 
                 safer_gnutls_strerror(ret));
 
491
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
492
            safer_gnutls_strerror(ret));
574
493
  }
575
494
  
576
495
  {
583
502
      }
584
503
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
585
504
    if(ret != GNUTLS_E_SUCCESS){
586
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
587
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
588
 
                   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));
589
508
      gnutls_deinit(*session);
590
509
      return -1;
591
510
    }
600
519
    }
601
520
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
602
521
  if(ret != GNUTLS_E_SUCCESS){
603
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
604
 
                 safer_gnutls_strerror(ret));
 
522
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
523
            safer_gnutls_strerror(ret));
605
524
    gnutls_deinit(*session);
606
525
    return -1;
607
526
  }
619
538
                      __attribute__((unused)) const char *txt){}
620
539
 
621
540
/* Called when a Mandos server is found */
622
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
541
static int start_mandos_communication(const char *ip, uint16_t port,
623
542
                                      AvahiIfIndex if_index,
624
543
                                      int af){
625
544
  int ret, tcp_sd = -1;
652
571
    pf = PF_INET;
653
572
    break;
654
573
  default:
655
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
574
    fprintf(stderr, "Bad address family: %d\n", af);
656
575
    errno = EINVAL;
657
576
    return -1;
658
577
  }
663
582
  }
664
583
  
665
584
  if(debug){
666
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
667
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
585
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
586
            "\n", ip, port);
668
587
  }
669
588
  
670
589
  tcp_sd = socket(pf, SOCK_STREAM, 0);
671
590
  if(tcp_sd < 0){
672
591
    int e = errno;
673
 
    perror_plus("socket");
 
592
    perror("socket");
674
593
    errno = e;
675
594
    goto mandos_end;
676
595
  }
690
609
  }
691
610
  if(ret < 0 ){
692
611
    int e = errno;
693
 
    perror_plus("inet_pton");
 
612
    perror("inet_pton");
694
613
    errno = e;
695
614
    goto mandos_end;
696
615
  }
697
616
  if(ret == 0){
698
617
    int e = errno;
699
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
618
    fprintf(stderr, "Bad address: %s\n", ip);
700
619
    errno = e;
701
620
    goto mandos_end;
702
621
  }
703
622
  if(af == AF_INET6){
704
 
    to.in6.sin6_port = htons(port);    
 
623
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
624
                                       -Wconversion and
 
625
                                       -Wunreachable-code */
 
626
    
705
627
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
706
628
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
707
 
                                -Wunreachable-code*/
 
629
                              -Wunreachable-code*/
708
630
      if(if_index == AVAHI_IF_UNSPEC){
709
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
710
 
                     " incomplete without a network interface\n");
 
631
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
632
                " without a network interface\n");
711
633
        errno = EINVAL;
712
634
        goto mandos_end;
713
635
      }
729
651
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
730
652
      char interface[IF_NAMESIZE];
731
653
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
732
 
        perror_plus("if_indextoname");
 
654
        perror("if_indextoname");
733
655
      } else {
734
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
735
 
                     "\n", ip, interface, (uintmax_t)port);
 
656
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
657
                ip, interface, port);
736
658
      }
737
659
    } else {
738
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
739
 
                   ip, (uintmax_t)port);
 
660
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
661
              port);
740
662
    }
741
663
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
742
664
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
749
671
                        sizeof(addrstr));
750
672
    }
751
673
    if(pcret == NULL){
752
 
      perror_plus("inet_ntop");
 
674
      perror("inet_ntop");
753
675
    } else {
754
676
      if(strcmp(addrstr, ip) != 0){
755
 
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
 
677
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
756
678
      }
757
679
    }
758
680
  }
770
692
  if(ret < 0){
771
693
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
772
694
      int e = errno;
773
 
      perror_plus("connect");
 
695
      perror("connect");
774
696
      errno = e;
775
697
    }
776
698
    goto mandos_end;
786
708
  while(true){
787
709
    size_t out_size = strlen(out);
788
710
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
789
 
                                        out_size - written));
 
711
                                   out_size - written));
790
712
    if(ret == -1){
791
713
      int e = errno;
792
 
      perror_plus("write");
 
714
      perror("write");
793
715
      errno = e;
794
716
      goto mandos_end;
795
717
    }
812
734
  }
813
735
  
814
736
  if(debug){
815
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
737
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
816
738
  }
817
739
  
818
740
  if(quit_now){
820
742
    goto mandos_end;
821
743
  }
822
744
  
823
 
  /* This casting via intptr_t is to eliminate warning about casting
824
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
825
 
     function "set-session-transport-fd!" does it. */
826
 
  gnutls_transport_set_ptr(session,
827
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
745
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
828
746
  
829
747
  if(quit_now){
830
748
    errno = EINTR;
841
759
  
842
760
  if(ret != GNUTLS_E_SUCCESS){
843
761
    if(debug){
844
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
762
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
845
763
      gnutls_perror(ret);
846
764
    }
847
765
    errno = EPROTO;
851
769
  /* Read OpenPGP packet that contains the wanted password */
852
770
  
853
771
  if(debug){
854
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
855
 
                 " %s\n", ip);
 
772
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
773
            ip);
856
774
  }
857
775
  
858
776
  while(true){
863
781
    }
864
782
    
865
783
    buffer_capacity = incbuffer(&buffer, buffer_length,
866
 
                                buffer_capacity);
 
784
                                   buffer_capacity);
867
785
    if(buffer_capacity == 0){
868
786
      int e = errno;
869
 
      perror_plus("incbuffer");
 
787
      perror("incbuffer");
870
788
      errno = e;
871
789
      goto mandos_end;
872
790
    }
896
814
          }
897
815
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
898
816
        if(ret < 0){
899
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
900
 
                       "***\n");
 
817
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
901
818
          gnutls_perror(ret);
902
819
          errno = EPROTO;
903
820
          goto mandos_end;
904
821
        }
905
822
        break;
906
823
      default:
907
 
        fprintf_plus(stderr, "Unknown error while reading data from"
908
 
                     " encrypted session with Mandos server\n");
 
824
        fprintf(stderr, "Unknown error while reading data from"
 
825
                " encrypted session with Mandos server\n");
909
826
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
910
827
        errno = EIO;
911
828
        goto mandos_end;
916
833
  }
917
834
  
918
835
  if(debug){
919
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
836
    fprintf(stderr, "Closing TLS session\n");
920
837
  }
921
838
  
922
839
  if(quit_now){
934
851
  
935
852
  if(buffer_length > 0){
936
853
    ssize_t decrypted_buffer_size;
937
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
854
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
855
                                               buffer_length,
938
856
                                               &decrypted_buffer);
939
857
    if(decrypted_buffer_size >= 0){
940
858
      
951
869
        if(ret == 0 and ferror(stdout)){
952
870
          int e = errno;
953
871
          if(debug){
954
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
955
 
                         strerror(errno));
 
872
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
873
                    strerror(errno));
956
874
          }
957
875
          errno = e;
958
876
          goto mandos_end;
977
895
      if(e == 0){
978
896
        e = errno;
979
897
      }
980
 
      perror_plus("close");
 
898
      perror("close");
981
899
    }
982
900
    gnutls_deinit(session);
983
 
    errno = e;
984
901
    if(quit_now){
985
 
      errno = EINTR;
 
902
      e = EINTR;
986
903
      retval = -1;
987
904
    }
 
905
    errno = e;
988
906
  }
989
907
  return retval;
990
908
}
1003
921
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1004
922
                             flags,
1005
923
                             AVAHI_GCC_UNUSED void* userdata){
1006
 
  if(r == NULL){
1007
 
    return;
1008
 
  }
 
924
  assert(r);
1009
925
  
1010
926
  /* Called whenever a service has been resolved successfully or
1011
927
     timed out */
1017
933
  switch(event){
1018
934
  default:
1019
935
  case AVAHI_RESOLVER_FAILURE:
1020
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1021
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1022
 
                 domain,
1023
 
                 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)));
1024
939
    break;
1025
940
    
1026
941
  case AVAHI_RESOLVER_FOUND:
1028
943
      char ip[AVAHI_ADDRESS_STR_MAX];
1029
944
      avahi_address_snprint(ip, sizeof(ip), address);
1030
945
      if(debug){
1031
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1032
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1033
 
                     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);
1034
949
      }
1035
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1036
 
                                           interface,
 
950
      int ret = start_mandos_communication(ip, port, interface,
1037
951
                                           avahi_proto_to_af(proto));
1038
952
      if(ret == 0){
1039
 
        avahi_simple_poll_quit(simple_poll);
1040
 
      } else {
1041
 
        if(not add_server(ip, (in_port_t)port, interface,
1042
 
                          avahi_proto_to_af(proto))){
1043
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1044
 
                       " list\n", name);
1045
 
        }
 
953
        avahi_simple_poll_quit(mc.simple_poll);
1046
954
      }
1047
955
    }
1048
956
  }
1059
967
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1060
968
                            flags,
1061
969
                            AVAHI_GCC_UNUSED void* userdata){
1062
 
  if(b == NULL){
1063
 
    return;
1064
 
  }
 
970
  assert(b);
1065
971
  
1066
972
  /* Called whenever a new services becomes available on the LAN or
1067
973
     is removed from the LAN */
1074
980
  default:
1075
981
  case AVAHI_BROWSER_FAILURE:
1076
982
    
1077
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1078
 
                 avahi_strerror(avahi_server_errno(mc.server)));
1079
 
    avahi_simple_poll_quit(simple_poll);
 
983
    fprintf(stderr, "(Avahi browser) %s\n",
 
984
            avahi_strerror(avahi_server_errno(mc.server)));
 
985
    avahi_simple_poll_quit(mc.simple_poll);
1080
986
    return;
1081
987
    
1082
988
  case AVAHI_BROWSER_NEW:
1088
994
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1089
995
                                    name, type, domain, protocol, 0,
1090
996
                                    resolve_callback, NULL) == NULL)
1091
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1092
 
                   " %s\n", name,
1093
 
                   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)));
1094
999
    break;
1095
1000
    
1096
1001
  case AVAHI_BROWSER_REMOVE:
1099
1004
  case AVAHI_BROWSER_ALL_FOR_NOW:
1100
1005
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1101
1006
    if(debug){
1102
 
      fprintf_plus(stderr, "No Mandos server found, still"
1103
 
                   " searching...\n");
 
1007
      fprintf(stderr, "No Mandos server found, still searching...\n");
1104
1008
    }
1105
1009
    break;
1106
1010
  }
1107
1011
}
1108
1012
 
1109
 
/* Signal handler that stops main loop after SIGTERM */
 
1013
/* stop main loop after sigterm has been called */
1110
1014
static void handle_sigterm(int sig){
1111
1015
  if(quit_now){
1112
1016
    return;
1114
1018
  quit_now = 1;
1115
1019
  signal_received = sig;
1116
1020
  int old_errno = errno;
1117
 
  /* set main loop to exit */
1118
 
  if(simple_poll != NULL){
1119
 
    avahi_simple_poll_quit(simple_poll);
 
1021
  if(mc.simple_poll != NULL){
 
1022
    avahi_simple_poll_quit(mc.simple_poll);
1120
1023
  }
1121
1024
  errno = old_errno;
1122
1025
}
1123
1026
 
1124
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1125
 
  int ret;
1126
 
  error_t ret_errno;
1127
 
  
1128
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1129
 
  if(s < 0){
1130
 
    ret_errno = errno;
1131
 
    perror_plus("socket");
1132
 
    errno = ret_errno;
1133
 
    return false;
1134
 
  }
1135
 
  strcpy(ifr->ifr_name, ifname);
1136
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1137
 
  if(ret == -1){
1138
 
    if(debug){
1139
 
      ret_errno = errno;
1140
 
      perror_plus("ioctl SIOCGIFFLAGS");
1141
 
      errno = ret_errno;
1142
 
    }
1143
 
    return false;
1144
 
  }
1145
 
  return true;
1146
 
}
1147
 
 
1148
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1149
 
  
1150
 
  /* Reject the loopback device */
1151
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
1152
 
    if(debug){
1153
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1154
 
                   ifname);
1155
 
    }
1156
 
    return false;
1157
 
  }
1158
 
  /* Accept point-to-point devices only if connect_to is specified */
1159
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1160
 
    if(debug){
1161
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1162
 
                   " \"%s\"\n", ifname);
1163
 
    }
1164
 
    return true;
1165
 
  }
1166
 
  /* Otherwise, reject non-broadcast-capable devices */
1167
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1168
 
    if(debug){
1169
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1170
 
                   " \"%s\"\n", ifname);
1171
 
    }
1172
 
    return false;
1173
 
  }
1174
 
  /* Reject non-ARP interfaces (including dummy interfaces) */
1175
 
  if(ifr->ifr_flags & IFF_NOARP){
1176
 
    if(debug){
1177
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1178
 
                   ifname);
1179
 
    }
1180
 
    return false;
1181
 
  }
1182
 
  
1183
 
  /* Accept this device */
1184
 
  if(debug){
1185
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1186
 
  }
1187
 
  return true;
1188
 
}
1189
 
 
1190
1027
/* 
1191
1028
 * This function determines if a directory entry in /sys/class/net
1192
1029
 * corresponds to an acceptable network device.
1193
1030
 * (This function is passed to scandir(3) as a filter function.)
1194
1031
 */
1195
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
  }
1196
1041
  if(if_entry->d_name[0] == '.'){
1197
1042
    return 0;
1198
1043
  }
1199
 
  
1200
 
  struct ifreq ifr;
1201
 
  if(not get_flags(if_entry->d_name, &ifr)){
1202
 
    if(debug){
1203
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1204
 
                   "\"%s\"\n", if_entry->d_name);
1205
 
    }
1206
 
    return 0;
1207
 
  }
1208
 
  
1209
 
  if(not good_flags(if_entry->d_name, &ifr)){
1210
 
    return 0;
1211
 
  }
1212
 
  return 1;
1213
 
}
1214
 
 
1215
 
/* 
1216
 
 * This function determines if a network interface is up.
1217
 
 */
1218
 
bool interface_is_up(const char *interface){
1219
 
  struct ifreq ifr;
1220
 
  if(not get_flags(interface, &ifr)){
1221
 
    if(debug){
1222
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1223
 
                   "\"%s\"\n", interface);
1224
 
    }
1225
 
    return false;
1226
 
  }
1227
 
  
1228
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1229
 
}
1230
 
 
1231
 
/* 
1232
 
 * This function determines if a network interface is running
1233
 
 */
1234
 
bool interface_is_running(const char *interface){
1235
 
  struct ifreq ifr;
1236
 
  if(not get_flags(interface, &ifr)){
1237
 
    if(debug){
1238
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1239
 
                   "\"%s\"\n", interface);
1240
 
    }
1241
 
    return false;
1242
 
  }
1243
 
  
1244
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1245
 
}
1246
 
 
1247
 
int notdotentries(const struct dirent *direntry){
1248
 
  /* Skip "." and ".." */
1249
 
  if(direntry->d_name[0] == '.'
1250
 
     and (direntry->d_name[1] == '\0'
1251
 
          or (direntry->d_name[1] == '.'
1252
 
              and direntry->d_name[2] == '\0'))){
1253
 
    return 0;
1254
 
  }
1255
 
  return 1;
1256
 
}
1257
 
 
1258
 
/* Is this directory entry a runnable program? */
1259
 
int runnable_hook(const struct dirent *direntry){
1260
 
  int ret;
1261
 
  size_t sret;
1262
 
  struct stat st;
1263
 
  
1264
 
  if((direntry->d_name)[0] == '\0'){
1265
 
    /* Empty name? */
1266
 
    return 0;
1267
 
  }
1268
 
  
1269
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1270
 
                "abcdefghijklmnopqrstuvwxyz"
1271
 
                "0123456789"
1272
 
                "_-");
1273
 
  if((direntry->d_name)[sret] != '\0'){
1274
 
    /* Contains non-allowed characters */
1275
 
    if(debug){
1276
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1277
 
                   direntry->d_name);
1278
 
    }
1279
 
    return 0;
1280
 
  }
1281
 
  
1282
 
  char *fullname = NULL;
1283
 
  ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1284
 
  if(ret < 0){
1285
 
    perror_plus("asprintf");
1286
 
    return 0;
1287
 
  }
1288
 
  
1289
 
  ret = stat(fullname, &st);
1290
 
  if(ret == -1){
1291
 
    if(debug){
1292
 
      perror_plus("Could not stat hook");
1293
 
    }
1294
 
    return 0;
1295
 
  }
1296
 
  if(not (S_ISREG(st.st_mode))){
1297
 
    /* Not a regular file */
1298
 
    if(debug){
1299
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1300
 
                   direntry->d_name);
1301
 
    }
1302
 
    return 0;
1303
 
  }
1304
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1305
 
    /* Not executable */
1306
 
    if(debug){
1307
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1308
 
                   direntry->d_name);
1309
 
    }
1310
 
    return 0;
1311
 
  }
 
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){
 
1081
    if(debug){
 
1082
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1083
              flagstring, if_entry->d_name);
 
1084
    }
 
1085
    free(flagstring);
 
1086
    return 0;
 
1087
  }
 
1088
  free(flagstring);
 
1089
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1090
  /* Reject the loopback device */
 
1091
  if(flags & IFF_LOOPBACK){
 
1092
    if(debug){
 
1093
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1094
              if_entry->d_name);
 
1095
    }
 
1096
    return 0;
 
1097
  }
 
1098
  /* Accept point-to-point devices only if connect_to is specified */
 
1099
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1100
    if(debug){
 
1101
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1102
              if_entry->d_name);
 
1103
    }
 
1104
    return 1;
 
1105
  }
 
1106
  /* Otherwise, reject non-broadcast-capable devices */
 
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
  }
 
1114
  /* Accept this device */
1312
1115
  if(debug){
1313
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1314
 
                 direntry->d_name);
 
1116
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1117
            if_entry->d_name);
1315
1118
  }
1316
1119
  return 1;
1317
1120
}
1318
1121
 
1319
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1320
 
  int ret;
1321
 
  struct timespec now;
1322
 
  struct timespec waited_time;
1323
 
  intmax_t block_time;
1324
 
  
1325
 
  while(true){
1326
 
    if(mc.current_server == NULL){
1327
 
      if (debug){
1328
 
        fprintf_plus(stderr, "Wait until first server is found."
1329
 
                     " No timeout!\n");
1330
 
      }
1331
 
      ret = avahi_simple_poll_iterate(s, -1);
1332
 
    } else {
1333
 
      if (debug){
1334
 
        fprintf_plus(stderr, "Check current_server if we should run"
1335
 
                     " it, or wait\n");
1336
 
      }
1337
 
      /* the current time */
1338
 
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1339
 
      if(ret == -1){
1340
 
        perror_plus("clock_gettime");
1341
 
        return -1;
1342
 
      }
1343
 
      /* Calculating in ms how long time between now and server
1344
 
         who we visted longest time ago. Now - last seen.  */
1345
 
      waited_time.tv_sec = (now.tv_sec
1346
 
                            - mc.current_server->last_seen.tv_sec);
1347
 
      waited_time.tv_nsec = (now.tv_nsec
1348
 
                             - mc.current_server->last_seen.tv_nsec);
1349
 
      /* total time is 10s/10,000ms.
1350
 
         Converting to s from ms by dividing by 1,000,
1351
 
         and ns to ms by dividing by 1,000,000. */
1352
 
      block_time = ((retry_interval
1353
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1354
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1355
 
      
1356
 
      if (debug){
1357
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1358
 
                     block_time);
1359
 
      }
1360
 
      
1361
 
      if(block_time <= 0){
1362
 
        ret = start_mandos_communication(mc.current_server->ip,
1363
 
                                         mc.current_server->port,
1364
 
                                         mc.current_server->if_index,
1365
 
                                         mc.current_server->af);
1366
 
        if(ret == 0){
1367
 
          avahi_simple_poll_quit(simple_poll);
1368
 
          return 0;
1369
 
        }
1370
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1371
 
                            &mc.current_server->last_seen);
1372
 
        if(ret == -1){
1373
 
          perror_plus("clock_gettime");
1374
 
          return -1;
1375
 
        }
1376
 
        mc.current_server = mc.current_server->next;
1377
 
        block_time = 0;         /* Call avahi to find new Mandos
1378
 
                                   servers, but don't block */
1379
 
      }
1380
 
      
1381
 
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1382
 
    }
1383
 
    if(ret != 0){
1384
 
      if (ret > 0 or errno != EINTR){
1385
 
        return (ret != 1) ? ret : 0;
1386
 
      }
1387
 
    }
1388
 
  }
1389
 
}
1390
 
 
1391
 
/* Set effective uid to 0, return errno */
1392
 
error_t raise_privileges(void){
1393
 
  error_t old_errno = errno;
1394
 
  error_t ret_errno = 0;
1395
 
  if(seteuid(0) == -1){
1396
 
    ret_errno = errno;
1397
 
    perror_plus("seteuid");
1398
 
  }
1399
 
  errno = old_errno;
1400
 
  return ret_errno;
1401
 
}
1402
 
 
1403
 
/* Set effective and real user ID to 0.  Return errno. */
1404
 
error_t raise_privileges_permanently(void){
1405
 
  error_t old_errno = errno;
1406
 
  error_t ret_errno = raise_privileges();
1407
 
  if(ret_errno != 0){
1408
 
    errno = old_errno;
1409
 
    return ret_errno;
1410
 
  }
1411
 
  if(setuid(0) == -1){
1412
 
    ret_errno = errno;
1413
 
    perror_plus("seteuid");
1414
 
  }
1415
 
  errno = old_errno;
1416
 
  return ret_errno;
1417
 
}
1418
 
 
1419
 
/* Set effective user ID to unprivileged saved user ID */
1420
 
error_t lower_privileges(void){
1421
 
  error_t old_errno = errno;
1422
 
  error_t ret_errno = 0;
1423
 
  if(seteuid(uid) == -1){
1424
 
    ret_errno = errno;
1425
 
    perror_plus("seteuid");
1426
 
  }
1427
 
  errno = old_errno;
1428
 
  return ret_errno;
1429
 
}
1430
 
 
1431
 
/* Lower privileges permanently */
1432
 
error_t lower_privileges_permanently(void){
1433
 
  error_t old_errno = errno;
1434
 
  error_t ret_errno = 0;
1435
 
  if(setuid(uid) == -1){
1436
 
    ret_errno = errno;
1437
 
    perror_plus("setuid");
1438
 
  }
1439
 
  errno = old_errno;
1440
 
  return ret_errno;
1441
 
}
1442
 
 
1443
 
bool run_network_hooks(const char *mode, const char *interface,
1444
 
                       const float delay){
1445
 
  struct dirent **direntries;
1446
 
  struct dirent *direntry;
1447
 
  int ret;
1448
 
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
1449
 
                         alphasort);
1450
 
  if(numhooks == -1){
1451
 
    if(errno == ENOENT){
1452
 
      if(debug){
1453
 
        fprintf_plus(stderr, "Network hook directory \"%s\" not"
1454
 
                     " found\n", hookdir);
1455
 
      }
1456
 
    } else {
1457
 
      perror_plus("scandir");
1458
 
    }
1459
 
  } else {
1460
 
    int devnull = open("/dev/null", O_RDONLY);
1461
 
    for(int i = 0; i < numhooks; i++){
1462
 
      direntry = direntries[i];
1463
 
      char *fullname = NULL;
1464
 
      ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name);
1465
 
      if(ret < 0){
1466
 
        perror_plus("asprintf");
1467
 
        continue;
1468
 
      }
1469
 
      if(debug){
1470
 
        fprintf_plus(stderr, "Running network hook \"%s\"\n",
1471
 
                     direntry->d_name);
1472
 
      }
1473
 
      pid_t hook_pid = fork();
1474
 
      if(hook_pid == 0){
1475
 
        /* Child */
1476
 
        /* Raise privileges */
1477
 
        raise_privileges_permanently();
1478
 
        /* Set group */
1479
 
        errno = 0;
1480
 
        ret = setgid(0);
1481
 
        if(ret == -1){
1482
 
          perror_plus("setgid");
1483
 
        }
1484
 
        /* Reset supplementary groups */
1485
 
        errno = 0;
1486
 
        ret = setgroups(0, NULL);
1487
 
        if(ret == -1){
1488
 
          perror_plus("setgroups");
1489
 
        }
1490
 
        dup2(devnull, STDIN_FILENO);
1491
 
        close(devnull);
1492
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1493
 
        ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1494
 
        if(ret == -1){
1495
 
          perror_plus("setenv");
1496
 
          _exit(EX_OSERR);
1497
 
        }
1498
 
        ret = setenv("DEVICE", interface, 1);
1499
 
        if(ret == -1){
1500
 
          perror_plus("setenv");
1501
 
          _exit(EX_OSERR);
1502
 
        }
1503
 
        ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1504
 
        if(ret == -1){
1505
 
          perror_plus("setenv");
1506
 
          _exit(EX_OSERR);
1507
 
        }
1508
 
        ret = setenv("MODE", mode, 1);
1509
 
        if(ret == -1){
1510
 
          perror_plus("setenv");
1511
 
          _exit(EX_OSERR);
1512
 
        }
1513
 
        char *delaystring;
1514
 
        ret = asprintf(&delaystring, "%f", delay);
1515
 
        if(ret == -1){
1516
 
          perror_plus("asprintf");
1517
 
          _exit(EX_OSERR);
1518
 
        }
1519
 
        ret = setenv("DELAY", delaystring, 1);
1520
 
        if(ret == -1){
1521
 
          free(delaystring);
1522
 
          perror_plus("setenv");
1523
 
          _exit(EX_OSERR);
1524
 
        }
1525
 
        free(delaystring);
1526
 
        if(connect_to != NULL){
1527
 
          ret = setenv("CONNECT", connect_to, 1);
1528
 
          if(ret == -1){
1529
 
            perror_plus("setenv");
1530
 
            _exit(EX_OSERR);
1531
 
          }
1532
 
        }
1533
 
        if(execl(fullname, direntry->d_name, mode, NULL) == -1){
1534
 
          perror_plus("execl");
1535
 
          _exit(EXIT_FAILURE);
1536
 
        }
1537
 
      } else {
1538
 
        int status;
1539
 
        if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
1540
 
          perror_plus("waitpid");
1541
 
          free(fullname);
1542
 
          continue;
1543
 
        }
1544
 
        if(WIFEXITED(status)){
1545
 
          if(WEXITSTATUS(status) != 0){
1546
 
            fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
1547
 
                         " with status %d\n", direntry->d_name,
1548
 
                         WEXITSTATUS(status));
1549
 
            free(fullname);
1550
 
            continue;
1551
 
          }
1552
 
        } else if(WIFSIGNALED(status)){
1553
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
1554
 
                       " signal %d\n", direntry->d_name,
1555
 
                       WTERMSIG(status));
1556
 
          free(fullname);
1557
 
          continue;
1558
 
        } else {
1559
 
          fprintf_plus(stderr, "Warning: network hook \"%s\""
1560
 
                       " crashed\n", direntry->d_name);
1561
 
          free(fullname);
1562
 
          continue;
1563
 
        }
1564
 
      }
1565
 
      free(fullname);
1566
 
      if(debug){
1567
 
        fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
1568
 
                     direntry->d_name);
1569
 
      }
1570
 
    }
1571
 
    close(devnull);
1572
 
  }
1573
 
  return true;
1574
 
}
1575
 
 
1576
 
error_t bring_up_interface(const char *const interface,
1577
 
                           const float delay){
1578
 
  int sd = -1;
1579
 
  error_t old_errno = errno;
1580
 
  error_t ret_errno = 0;
1581
 
  int ret, ret_setflags;
1582
 
  struct ifreq network;
1583
 
  unsigned int if_index = if_nametoindex(interface);
1584
 
  if(if_index == 0){
1585
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1586
 
    errno = old_errno;
1587
 
    return ENXIO;
1588
 
  }
1589
 
  
1590
 
  if(quit_now){
1591
 
    errno = old_errno;
1592
 
    return EINTR;
1593
 
  }
1594
 
  
1595
 
  if(not interface_is_up(interface)){
1596
 
    if(not get_flags(interface, &network) and debug){
1597
 
      ret_errno = errno;
1598
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1599
 
                   "\"%s\"\n", interface);
1600
 
      return ret_errno;
1601
 
    }
1602
 
    network.ifr_flags |= IFF_UP;
1603
 
    
1604
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1605
 
    if(sd < 0){
1606
 
      ret_errno = errno;
1607
 
      perror_plus("socket");
1608
 
      errno = old_errno;
1609
 
      return ret_errno;
1610
 
    }
1611
 
  
1612
 
    if(quit_now){
1613
 
      close(sd);
1614
 
      errno = old_errno;
1615
 
      return EINTR;
1616
 
    }
1617
 
    
1618
 
    if(debug){
1619
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
1620
 
                   interface);
1621
 
    }
1622
 
    
1623
 
    /* Raise priviliges */
1624
 
    raise_privileges();
1625
 
    
1626
 
#ifdef __linux__
1627
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1628
 
       messages about the network interface to mess up the prompt */
1629
 
    int ret_linux = klogctl(8, NULL, 5);
1630
 
    bool restore_loglevel = true;
1631
 
    if(ret_linux == -1){
1632
 
      restore_loglevel = false;
1633
 
      perror_plus("klogctl");
1634
 
    }
1635
 
#endif  /* __linux__ */
1636
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1637
 
    ret_errno = errno;
1638
 
#ifdef __linux__
1639
 
    if(restore_loglevel){
1640
 
      ret_linux = klogctl(7, NULL, 0);
1641
 
      if(ret_linux == -1){
1642
 
        perror_plus("klogctl");
1643
 
      }
1644
 
    }
1645
 
#endif  /* __linux__ */
1646
 
    
1647
 
    /* Lower privileges */
1648
 
    lower_privileges();
1649
 
    
1650
 
    /* Close the socket */
1651
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1652
 
    if(ret == -1){
1653
 
      perror_plus("close");
1654
 
    }
1655
 
    
1656
 
    if(ret_setflags == -1){
1657
 
      errno = ret_errno;
1658
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1659
 
      errno = old_errno;
1660
 
      return ret_errno;
1661
 
    }
1662
 
  } else if(debug){
1663
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
1664
 
                 interface);
1665
 
  }
1666
 
  
1667
 
  /* Sleep checking until interface is running.
1668
 
     Check every 0.25s, up to total time of delay */
1669
 
  for(int i=0; i < delay * 4; i++){
1670
 
    if(interface_is_running(interface)){
1671
 
      break;
1672
 
    }
1673
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
1674
 
    ret = nanosleep(&sleeptime, NULL);
1675
 
    if(ret == -1 and errno != EINTR){
1676
 
      perror_plus("nanosleep");
1677
 
    }
1678
 
  }
1679
 
  
1680
 
  errno = old_errno;
1681
 
  return 0;
1682
 
}
1683
 
 
1684
 
error_t take_down_interface(const char *const interface){
1685
 
  int sd = -1;
1686
 
  error_t old_errno = errno;
1687
 
  error_t ret_errno = 0;
1688
 
  int ret, ret_setflags;
1689
 
  struct ifreq network;
1690
 
  unsigned int if_index = if_nametoindex(interface);
1691
 
  if(if_index == 0){
1692
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1693
 
    errno = old_errno;
1694
 
    return ENXIO;
1695
 
  }
1696
 
  if(interface_is_up(interface)){
1697
 
    if(not get_flags(interface, &network) and debug){
1698
 
      ret_errno = errno;
1699
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1700
 
                   "\"%s\"\n", interface);
1701
 
      return ret_errno;
1702
 
    }
1703
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1704
 
    
1705
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1706
 
    if(sd < 0){
1707
 
      ret_errno = errno;
1708
 
      perror_plus("socket");
1709
 
      errno = old_errno;
1710
 
      return ret_errno;
1711
 
    }
1712
 
    
1713
 
    if(debug){
1714
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
1715
 
                   interface);
1716
 
    }
1717
 
    
1718
 
    /* Raise priviliges */
1719
 
    raise_privileges();
1720
 
    
1721
 
    ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
1722
 
    ret_errno = errno;
1723
 
    
1724
 
    /* Lower privileges */
1725
 
    lower_privileges();
1726
 
    
1727
 
    /* Close the socket */
1728
 
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
1729
 
    if(ret == -1){
1730
 
      perror_plus("close");
1731
 
    }
1732
 
    
1733
 
    if(ret_setflags == -1){
1734
 
      errno = ret_errno;
1735
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1736
 
      errno = old_errno;
1737
 
      return ret_errno;
1738
 
    }
1739
 
  } else if(debug){
1740
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
1741
 
                 interface);
1742
 
  }
1743
 
  
1744
 
  errno = old_errno;
1745
 
  return 0;
1746
 
}
1747
 
 
1748
1122
int main(int argc, char *argv[]){
1749
1123
  AvahiSServiceBrowser *sb = NULL;
1750
 
  error_t ret_errno;
 
1124
  int error;
1751
1125
  int ret;
1752
1126
  intmax_t tmpmax;
1753
1127
  char *tmp;
1754
1128
  int exitcode = EXIT_SUCCESS;
1755
 
  char *interfaces = NULL;
1756
 
  size_t interfaces_size = 0;
1757
 
  char *interfaces_to_take_down = NULL;
1758
 
  size_t interfaces_to_take_down_size = 0;
 
1129
  const char *interface = "";
 
1130
  struct ifreq network;
 
1131
  int sd = -1;
 
1132
  bool take_down_interface = false;
 
1133
  uid_t uid;
 
1134
  gid_t gid;
1759
1135
  char tempdir[] = "/tmp/mandosXXXXXX";
1760
1136
  bool tempdir_created = false;
1761
1137
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1762
1138
  const char *seckey = PATHDIR "/" SECKEY;
1763
1139
  const char *pubkey = PATHDIR "/" PUBKEY;
1764
 
  char *interfaces_hooks = NULL;
1765
 
  size_t interfaces_hooks_size = 0;
1766
1140
  
1767
1141
  bool gnutls_initialized = false;
1768
1142
  bool gpgme_initialized = false;
1769
1143
  float delay = 2.5f;
1770
 
  double retry_interval = 10; /* 10s between trying a server and
1771
 
                                 retrying the same server again */
1772
1144
  
1773
1145
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1774
1146
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1780
1152
  errno = 0;
1781
1153
  ret = setgid(gid);
1782
1154
  if(ret == -1){
1783
 
    perror_plus("setgid");
 
1155
    perror("setgid");
1784
1156
  }
1785
1157
  
1786
1158
  /* Lower user privileges (temporarily) */
1787
1159
  errno = 0;
1788
1160
  ret = seteuid(uid);
1789
1161
  if(ret == -1){
1790
 
    perror_plus("seteuid");
 
1162
    perror("seteuid");
1791
1163
  }
1792
1164
  
1793
1165
  if(quit_now){
1828
1200
        .arg = "SECONDS",
1829
1201
        .doc = "Maximum delay to wait for interface startup",
1830
1202
        .group = 2 },
1831
 
      { .name = "retry", .key = 132,
1832
 
        .arg = "SECONDS",
1833
 
        .doc = "Retry interval used when denied by the Mandos server",
1834
 
        .group = 2 },
1835
 
      { .name = "network-hook-dir", .key = 133,
1836
 
        .arg = "DIR",
1837
 
        .doc = "Directory where network hooks are located",
1838
 
        .group = 2 },
1839
1203
      /*
1840
1204
       * These reproduce what we would get without ARGP_NO_HELP
1841
1205
       */
1859
1223
        connect_to = arg;
1860
1224
        break;
1861
1225
      case 'i':                 /* --interface */
1862
 
        ret_errno = argz_add_sep(&interfaces, &interfaces_size, arg,
1863
 
                                 (int)',');
1864
 
        if(ret_errno != 0){
1865
 
          argp_error(state, "%s", strerror(ret_errno));
1866
 
        }
 
1226
        interface = arg;
1867
1227
        break;
1868
1228
      case 's':                 /* --seckey */
1869
1229
        seckey = arg;
1889
1249
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1890
1250
          argp_error(state, "Bad delay");
1891
1251
        }
1892
 
      case 132:                 /* --retry */
1893
 
        errno = 0;
1894
 
        retry_interval = strtod(arg, &tmp);
1895
 
        if(errno != 0 or tmp == arg or *tmp != '\0'
1896
 
           or (retry_interval * 1000) > INT_MAX
1897
 
           or retry_interval < 0){
1898
 
          argp_error(state, "Bad retry interval");
1899
 
        }
1900
 
        break;
1901
 
      case 133:                 /* --network-hook-dir */
1902
 
        hookdir = arg;
1903
1252
        break;
1904
1253
        /*
1905
1254
         * These reproduce what we would get without ARGP_NO_HELP
1912
1261
        argp_state_help(state, state->out_stream,
1913
1262
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1914
1263
      case 'V':                 /* --version */
1915
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1264
        fprintf(state->out_stream, "%s\n", argp_program_version);
1916
1265
        exit(argp_err_exit_status);
1917
1266
        break;
1918
1267
      default:
1933
1282
    case ENOMEM:
1934
1283
    default:
1935
1284
      errno = ret;
1936
 
      perror_plus("argp_parse");
 
1285
      perror("argp_parse");
1937
1286
      exitcode = EX_OSERR;
1938
1287
      goto end;
1939
1288
    case EINVAL:
1941
1290
      goto end;
1942
1291
    }
1943
1292
  }
1944
 
    
1945
 
  {
1946
 
    /* Work around Debian bug #633582:
1947
 
       <http://bugs.debian.org/633582> */
1948
 
    
1949
 
    /* Re-raise priviliges */
1950
 
    if(raise_privileges() == 0){
1951
 
      struct stat st;
1952
 
      
1953
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1954
 
        int seckey_fd = open(seckey, O_RDONLY);
1955
 
        if(seckey_fd == -1){
1956
 
          perror_plus("open");
1957
 
        } else {
1958
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1959
 
          if(ret == -1){
1960
 
            perror_plus("fstat");
1961
 
          } else {
1962
 
            if(S_ISREG(st.st_mode)
1963
 
               and st.st_uid == 0 and st.st_gid == 0){
1964
 
              ret = fchown(seckey_fd, uid, gid);
1965
 
              if(ret == -1){
1966
 
                perror_plus("fchown");
1967
 
              }
1968
 
            }
1969
 
          }
1970
 
          TEMP_FAILURE_RETRY(close(seckey_fd));
1971
 
        }
1972
 
      }
1973
 
    
1974
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1975
 
        int pubkey_fd = open(pubkey, O_RDONLY);
1976
 
        if(pubkey_fd == -1){
1977
 
          perror_plus("open");
1978
 
        } else {
1979
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1980
 
          if(ret == -1){
1981
 
            perror_plus("fstat");
1982
 
          } else {
1983
 
            if(S_ISREG(st.st_mode)
1984
 
               and st.st_uid == 0 and st.st_gid == 0){
1985
 
              ret = fchown(pubkey_fd, uid, gid);
1986
 
              if(ret == -1){
1987
 
                perror_plus("fchown");
1988
 
              }
1989
 
            }
1990
 
          }
1991
 
          TEMP_FAILURE_RETRY(close(pubkey_fd));
1992
 
        }
1993
 
      }
1994
 
    
1995
 
      /* Lower privileges */
1996
 
      errno = 0;
1997
 
      ret = seteuid(uid);
1998
 
      if(ret == -1){
1999
 
        perror_plus("seteuid");
2000
 
      }
2001
 
    }
2002
 
  }
2003
 
  
2004
 
  /* Remove empty interface names */
2005
 
  {
2006
 
    char *interface = NULL;
2007
 
    while((interface = argz_next(interfaces, interfaces_size,
2008
 
                                 interface))){
2009
 
      if(if_nametoindex(interface) == 0){
2010
 
        if(interface[0] != '\0' and strcmp(interface, "none") != 0){
2011
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2012
 
                       " \"%s\"\n", interface);
2013
 
        }
2014
 
        argz_delete(&interfaces, &interfaces_size, interface);
2015
 
        interface = NULL;
2016
 
      }
2017
 
    }
2018
 
  }
2019
 
  
2020
 
  /* Run network hooks */
2021
 
  {
2022
 
    
2023
 
    if(interfaces != NULL){
2024
 
      interfaces_hooks = malloc(interfaces_size);
2025
 
      if(interfaces_hooks == NULL){
2026
 
        perror_plus("malloc");
2027
 
        goto end;
2028
 
      }
2029
 
      memcpy(interfaces_hooks, interfaces, interfaces_size);
2030
 
      interfaces_hooks_size = interfaces_size;
2031
 
      argz_stringify(interfaces_hooks, interfaces_hooks_size,
2032
 
                     (int)',');
2033
 
    }
2034
 
    if(not run_network_hooks("start", interfaces_hooks != NULL ?
2035
 
                             interfaces_hooks : "", delay)){
2036
 
      goto end;
2037
 
    }
2038
 
  }
2039
1293
  
2040
1294
  if(not debug){
2041
1295
    avahi_set_log_function(empty_log);
2042
1296
  }
 
1297
 
 
1298
  if(interface[0] == '\0'){
 
1299
    struct dirent **direntries;
 
1300
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1301
                  alphasort);
 
1302
    if(ret >= 1){
 
1303
      /* Pick the first good interface */
 
1304
      interface = strdup(direntries[0]->d_name);
 
1305
      if(debug){
 
1306
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1307
      }
 
1308
      if(interface == NULL){
 
1309
        perror("malloc");
 
1310
        free(direntries);
 
1311
        exitcode = EXIT_FAILURE;
 
1312
        goto end;
 
1313
      }
 
1314
      free(direntries);
 
1315
    } else {
 
1316
      free(direntries);
 
1317
      fprintf(stderr, "Could not find a network interface\n");
 
1318
      exitcode = EXIT_FAILURE;
 
1319
      goto end;
 
1320
    }
 
1321
  }
2043
1322
  
2044
1323
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2045
1324
     from the signal handler */
2046
1325
  /* Initialize the pseudo-RNG for Avahi */
2047
1326
  srand((unsigned int) time(NULL));
2048
 
  simple_poll = avahi_simple_poll_new();
2049
 
  if(simple_poll == NULL){
2050
 
    fprintf_plus(stderr,
2051
 
                 "Avahi: Failed to create simple poll object.\n");
 
1327
  mc.simple_poll = avahi_simple_poll_new();
 
1328
  if(mc.simple_poll == NULL){
 
1329
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
2052
1330
    exitcode = EX_UNAVAILABLE;
2053
1331
    goto end;
2054
1332
  }
2056
1334
  sigemptyset(&sigterm_action.sa_mask);
2057
1335
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
2058
1336
  if(ret == -1){
2059
 
    perror_plus("sigaddset");
 
1337
    perror("sigaddset");
2060
1338
    exitcode = EX_OSERR;
2061
1339
    goto end;
2062
1340
  }
2063
1341
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
2064
1342
  if(ret == -1){
2065
 
    perror_plus("sigaddset");
 
1343
    perror("sigaddset");
2066
1344
    exitcode = EX_OSERR;
2067
1345
    goto end;
2068
1346
  }
2069
1347
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
2070
1348
  if(ret == -1){
2071
 
    perror_plus("sigaddset");
 
1349
    perror("sigaddset");
2072
1350
    exitcode = EX_OSERR;
2073
1351
    goto end;
2074
1352
  }
2078
1356
  */
2079
1357
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
2080
1358
  if(ret == -1){
2081
 
    perror_plus("sigaction");
 
1359
    perror("sigaction");
2082
1360
    return EX_OSERR;
2083
1361
  }
2084
1362
  if(old_sigterm_action.sa_handler != SIG_IGN){
2085
1363
    ret = sigaction(SIGINT, &sigterm_action, NULL);
2086
1364
    if(ret == -1){
2087
 
      perror_plus("sigaction");
 
1365
      perror("sigaction");
2088
1366
      exitcode = EX_OSERR;
2089
1367
      goto end;
2090
1368
    }
2091
1369
  }
2092
1370
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
2093
1371
  if(ret == -1){
2094
 
    perror_plus("sigaction");
 
1372
    perror("sigaction");
2095
1373
    return EX_OSERR;
2096
1374
  }
2097
1375
  if(old_sigterm_action.sa_handler != SIG_IGN){
2098
1376
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
2099
1377
    if(ret == -1){
2100
 
      perror_plus("sigaction");
 
1378
      perror("sigaction");
2101
1379
      exitcode = EX_OSERR;
2102
1380
      goto end;
2103
1381
    }
2104
1382
  }
2105
1383
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
2106
1384
  if(ret == -1){
2107
 
    perror_plus("sigaction");
 
1385
    perror("sigaction");
2108
1386
    return EX_OSERR;
2109
1387
  }
2110
1388
  if(old_sigterm_action.sa_handler != SIG_IGN){
2111
1389
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
2112
1390
    if(ret == -1){
2113
 
      perror_plus("sigaction");
 
1391
      perror("sigaction");
2114
1392
      exitcode = EX_OSERR;
2115
1393
      goto end;
2116
1394
    }
2117
1395
  }
2118
1396
  
2119
 
  /* If no interfaces were specified, make a list */
2120
 
  if(interfaces == NULL){
2121
 
    struct dirent **direntries;
2122
 
    /* Look for any good interfaces */
2123
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2124
 
                  alphasort);
2125
 
    if(ret >= 1){
2126
 
      /* Add all found interfaces to interfaces list */
2127
 
      for(int i = 0; i < ret; ++i){
2128
 
        ret_errno = argz_add(&interfaces, &interfaces_size,
2129
 
                             direntries[i]->d_name);
2130
 
        if(ret_errno != 0){
2131
 
          perror_plus("argz_add");
2132
 
          continue;
2133
 
        }
2134
 
        if(debug){
2135
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2136
 
                       direntries[i]->d_name);
2137
 
        }
2138
 
      }
2139
 
      free(direntries);
 
1397
  /* If the interface is down, bring it up */
 
1398
  if(strcmp(interface, "none") != 0){
 
1399
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1400
    if(if_index == 0){
 
1401
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1402
      exitcode = EX_UNAVAILABLE;
 
1403
      goto end;
 
1404
    }
 
1405
    
 
1406
    if(quit_now){
 
1407
      goto end;
 
1408
    }
 
1409
    
 
1410
    /* Re-raise priviliges */
 
1411
    errno = 0;
 
1412
    ret = seteuid(0);
 
1413
    if(ret == -1){
 
1414
      perror("seteuid");
 
1415
    }
 
1416
    
 
1417
#ifdef __linux__
 
1418
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1419
       messages about the network interface to mess up the prompt */
 
1420
    ret = klogctl(8, NULL, 5);
 
1421
    bool restore_loglevel = true;
 
1422
    if(ret == -1){
 
1423
      restore_loglevel = false;
 
1424
      perror("klogctl");
 
1425
    }
 
1426
#endif  /* __linux__ */
 
1427
    
 
1428
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1429
    if(sd < 0){
 
1430
      perror("socket");
 
1431
      exitcode = EX_OSERR;
 
1432
#ifdef __linux__
 
1433
      if(restore_loglevel){
 
1434
        ret = klogctl(7, NULL, 0);
 
1435
        if(ret == -1){
 
1436
          perror("klogctl");
 
1437
        }
 
1438
      }
 
1439
#endif  /* __linux__ */
 
1440
      /* Lower privileges */
 
1441
      errno = 0;
 
1442
      ret = seteuid(uid);
 
1443
      if(ret == -1){
 
1444
        perror("seteuid");
 
1445
      }
 
1446
      goto end;
 
1447
    }
 
1448
    strcpy(network.ifr_name, interface);
 
1449
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1450
    if(ret == -1){
 
1451
      perror("ioctl SIOCGIFFLAGS");
 
1452
#ifdef __linux__
 
1453
      if(restore_loglevel){
 
1454
        ret = klogctl(7, NULL, 0);
 
1455
        if(ret == -1){
 
1456
          perror("klogctl");
 
1457
        }
 
1458
      }
 
1459
#endif  /* __linux__ */
 
1460
      exitcode = EX_OSERR;
 
1461
      /* Lower privileges */
 
1462
      errno = 0;
 
1463
      ret = seteuid(uid);
 
1464
      if(ret == -1){
 
1465
        perror("seteuid");
 
1466
      }
 
1467
      goto end;
 
1468
    }
 
1469
    if((network.ifr_flags & IFF_UP) == 0){
 
1470
      network.ifr_flags |= IFF_UP;
 
1471
      take_down_interface = true;
 
1472
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1473
      if(ret == -1){
 
1474
        take_down_interface = false;
 
1475
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1476
        exitcode = EX_OSERR;
 
1477
#ifdef __linux__
 
1478
        if(restore_loglevel){
 
1479
          ret = klogctl(7, NULL, 0);
 
1480
          if(ret == -1){
 
1481
            perror("klogctl");
 
1482
          }
 
1483
        }
 
1484
#endif  /* __linux__ */
 
1485
        /* Lower privileges */
 
1486
        errno = 0;
 
1487
        ret = seteuid(uid);
 
1488
        if(ret == -1){
 
1489
          perror("seteuid");
 
1490
        }
 
1491
        goto end;
 
1492
      }
 
1493
    }
 
1494
    /* sleep checking until interface is running */
 
1495
    for(int i=0; i < delay * 4; i++){
 
1496
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1497
      if(ret == -1){
 
1498
        perror("ioctl SIOCGIFFLAGS");
 
1499
      } else if(network.ifr_flags & IFF_RUNNING){
 
1500
        break;
 
1501
      }
 
1502
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1503
      ret = nanosleep(&sleeptime, NULL);
 
1504
      if(ret == -1 and errno != EINTR){
 
1505
        perror("nanosleep");
 
1506
      }
 
1507
    }
 
1508
    if(not take_down_interface){
 
1509
      /* We won't need the socket anymore */
 
1510
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1511
      if(ret == -1){
 
1512
        perror("close");
 
1513
      }
 
1514
    }
 
1515
#ifdef __linux__
 
1516
    if(restore_loglevel){
 
1517
      /* Restores kernel loglevel to default */
 
1518
      ret = klogctl(7, NULL, 0);
 
1519
      if(ret == -1){
 
1520
        perror("klogctl");
 
1521
      }
 
1522
    }
 
1523
#endif  /* __linux__ */
 
1524
    /* Lower privileges */
 
1525
    errno = 0;
 
1526
    if(take_down_interface){
 
1527
      /* Lower privileges */
 
1528
      ret = seteuid(uid);
 
1529
      if(ret == -1){
 
1530
        perror("seteuid");
 
1531
      }
2140
1532
    } else {
2141
 
      free(direntries);
2142
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2143
 
      exitcode = EXIT_FAILURE;
2144
 
      goto end;
2145
 
    }
2146
 
  }
2147
 
  
2148
 
  /* If we only got one interface, explicitly use only that one */
2149
 
  if(argz_count(interfaces, interfaces_size) == 1){
2150
 
    if(debug){
2151
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2152
 
                   interfaces);
2153
 
    }
2154
 
    if_index = (AvahiIfIndex)if_nametoindex(interfaces);
2155
 
  }
2156
 
  
2157
 
  /* Bring up interfaces which are down */
2158
 
  if(not (argz_count(interfaces, interfaces_size) == 1
2159
 
          and strcmp(interfaces, "none") == 0)){
2160
 
    char *interface = NULL;
2161
 
    while((interface = argz_next(interfaces, interfaces_size,
2162
 
                                 interface))){
2163
 
      bool interface_was_up = interface_is_up(interface);
2164
 
      ret = bring_up_interface(interface, delay);
2165
 
      if(not interface_was_up){
2166
 
        if(ret != 0){
2167
 
          errno = ret;
2168
 
          perror_plus("Failed to bring up interface");
2169
 
        } else {
2170
 
          ret_errno = argz_add(&interfaces_to_take_down,
2171
 
                               &interfaces_to_take_down_size,
2172
 
                               interface);
2173
 
        }
 
1533
      /* Lower privileges permanently */
 
1534
      ret = setuid(uid);
 
1535
      if(ret == -1){
 
1536
        perror("setuid");
2174
1537
      }
2175
1538
    }
2176
 
    free(interfaces);
2177
 
    interfaces = NULL;
2178
 
    interfaces_size = 0;
2179
 
    if(debug and (interfaces_to_take_down == NULL)){
2180
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2181
 
    }
2182
1539
  }
2183
1540
  
2184
1541
  if(quit_now){
2187
1544
  
2188
1545
  ret = init_gnutls_global(pubkey, seckey);
2189
1546
  if(ret == -1){
2190
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1547
    fprintf(stderr, "init_gnutls_global failed\n");
2191
1548
    exitcode = EX_UNAVAILABLE;
2192
1549
    goto end;
2193
1550
  } else {
2198
1555
    goto end;
2199
1556
  }
2200
1557
  
 
1558
  tempdir_created = true;
2201
1559
  if(mkdtemp(tempdir) == NULL){
2202
 
    perror_plus("mkdtemp");
 
1560
    tempdir_created = false;
 
1561
    perror("mkdtemp");
2203
1562
    goto end;
2204
1563
  }
2205
 
  tempdir_created = true;
2206
1564
  
2207
1565
  if(quit_now){
2208
1566
    goto end;
2209
1567
  }
2210
1568
  
2211
1569
  if(not init_gpgme(pubkey, seckey, tempdir)){
2212
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1570
    fprintf(stderr, "init_gpgme failed\n");
2213
1571
    exitcode = EX_UNAVAILABLE;
2214
1572
    goto end;
2215
1573
  } else {
2224
1582
    /* Connect directly, do not use Zeroconf */
2225
1583
    /* (Mainly meant for debugging) */
2226
1584
    char *address = strrchr(connect_to, ':');
2227
 
    
2228
1585
    if(address == NULL){
2229
 
      fprintf_plus(stderr, "No colon in address\n");
 
1586
      fprintf(stderr, "No colon in address\n");
2230
1587
      exitcode = EX_USAGE;
2231
1588
      goto end;
2232
1589
    }
2235
1592
      goto end;
2236
1593
    }
2237
1594
    
2238
 
    in_port_t port;
 
1595
    uint16_t port;
2239
1596
    errno = 0;
2240
1597
    tmpmax = strtoimax(address+1, &tmp, 10);
2241
1598
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2242
 
       or tmpmax != (in_port_t)tmpmax){
2243
 
      fprintf_plus(stderr, "Bad port number\n");
 
1599
       or tmpmax != (uint16_t)tmpmax){
 
1600
      fprintf(stderr, "Bad port number\n");
2244
1601
      exitcode = EX_USAGE;
2245
1602
      goto end;
2246
1603
    }
2249
1606
      goto end;
2250
1607
    }
2251
1608
    
2252
 
    port = (in_port_t)tmpmax;
 
1609
    port = (uint16_t)tmpmax;
2253
1610
    *address = '\0';
 
1611
    address = connect_to;
2254
1612
    /* Colon in address indicates IPv6 */
2255
1613
    int af;
2256
 
    if(strchr(connect_to, ':') != NULL){
 
1614
    if(strchr(address, ':') != NULL){
2257
1615
      af = AF_INET6;
2258
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2259
 
      if(connect_to[0] == '[' and address[-1] == ']')
2260
 
        {
2261
 
          connect_to++;
2262
 
          address[-1] = '\0';
2263
 
        }
2264
1616
    } else {
2265
1617
      af = AF_INET;
2266
1618
    }
2267
 
    address = connect_to;
2268
1619
    
2269
1620
    if(quit_now){
2270
1621
      goto end;
2271
1622
    }
2272
 
    
 
1623
 
2273
1624
    while(not quit_now){
2274
1625
      ret = start_mandos_communication(address, port, if_index, af);
2275
1626
      if(quit_now or ret == 0){
2276
1627
        break;
2277
1628
      }
2278
 
      if(debug){
2279
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2280
 
                     (int)retry_interval);
2281
 
      }
2282
 
      sleep((int)retry_interval);
2283
 
    }
2284
 
    
 
1629
      sleep(15);
 
1630
    };
 
1631
 
2285
1632
    if (not quit_now){
2286
1633
      exitcode = EXIT_SUCCESS;
2287
1634
    }
2288
 
    
 
1635
 
2289
1636
    goto end;
2290
1637
  }
2291
1638
  
2303
1650
    config.publish_domain = 0;
2304
1651
    
2305
1652
    /* Allocate a new server */
2306
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2307
 
                                 &config, NULL, NULL, &ret_errno);
 
1653
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1654
                                 (mc.simple_poll), &config, NULL,
 
1655
                                 NULL, &error);
2308
1656
    
2309
1657
    /* Free the Avahi configuration data */
2310
1658
    avahi_server_config_free(&config);
2312
1660
  
2313
1661
  /* Check if creating the Avahi server object succeeded */
2314
1662
  if(mc.server == NULL){
2315
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2316
 
                 avahi_strerror(ret_errno));
 
1663
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1664
            avahi_strerror(error));
2317
1665
    exitcode = EX_UNAVAILABLE;
2318
1666
    goto end;
2319
1667
  }
2327
1675
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2328
1676
                                   NULL, 0, browse_callback, NULL);
2329
1677
  if(sb == NULL){
2330
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2331
 
                 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)));
2332
1680
    exitcode = EX_UNAVAILABLE;
2333
1681
    goto end;
2334
1682
  }
2340
1688
  /* Run the main loop */
2341
1689
  
2342
1690
  if(debug){
2343
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2344
 
  }
2345
 
 
2346
 
  ret = avahi_loop_with_timeout(simple_poll,
2347
 
                                (int)(retry_interval * 1000));
2348
 
  if(debug){
2349
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2350
 
                 (ret == 0) ? "successfully" : "with error");
2351
 
  }
 
1691
    fprintf(stderr, "Starting Avahi loop search\n");
 
1692
  }
 
1693
  
 
1694
  avahi_simple_poll_loop(mc.simple_poll);
2352
1695
  
2353
1696
 end:
2354
1697
  
2355
1698
  if(debug){
2356
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1699
    fprintf(stderr, "%s exiting\n", argv[0]);
2357
1700
  }
2358
1701
  
2359
1702
  /* Cleanup things */
2363
1706
  if(mc.server != NULL)
2364
1707
    avahi_server_free(mc.server);
2365
1708
  
2366
 
  if(simple_poll != NULL)
2367
 
    avahi_simple_poll_free(simple_poll);
 
1709
  if(mc.simple_poll != NULL)
 
1710
    avahi_simple_poll_free(mc.simple_poll);
2368
1711
  
2369
1712
  if(gnutls_initialized){
2370
1713
    gnutls_certificate_free_credentials(mc.cred);
2376
1719
    gpgme_release(mc.ctx);
2377
1720
  }
2378
1721
  
2379
 
  /* Cleans up the circular linked list of Mandos servers the client
2380
 
     has seen */
2381
 
  if(mc.current_server != NULL){
2382
 
    mc.current_server->prev->next = NULL;
2383
 
    while(mc.current_server != NULL){
2384
 
      server *next = mc.current_server->next;
2385
 
      free(mc.current_server);
2386
 
      mc.current_server = next;
 
1722
  /* Take down the network interface */
 
1723
  if(take_down_interface){
 
1724
    /* Re-raise priviliges */
 
1725
    errno = 0;
 
1726
    ret = seteuid(0);
 
1727
    if(ret == -1){
 
1728
      perror("seteuid");
2387
1729
    }
2388
 
  }
2389
 
  
2390
 
  /* Re-raise priviliges */
2391
 
  {
2392
 
    raise_privileges();
2393
 
    
2394
 
    /* Run network hooks */
2395
 
    run_network_hooks("stop", interfaces_hooks != NULL ?
2396
 
                      interfaces_hooks : "", delay);
2397
 
    
2398
 
    /* Take down the network interfaces which were brought up */
2399
 
    {
2400
 
      char *interface = NULL;
2401
 
      while((interface=argz_next(interfaces_to_take_down,
2402
 
                                 interfaces_to_take_down_size,
2403
 
                                 interface))){
2404
 
        ret_errno = take_down_interface(interface);
2405
 
        if(ret_errno != 0){
2406
 
          errno = ret_errno;
2407
 
          perror_plus("Failed to take down interface");
 
1730
    if(geteuid() == 0){
 
1731
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1732
      if(ret == -1){
 
1733
        perror("ioctl SIOCGIFFLAGS");
 
1734
      } else if(network.ifr_flags & IFF_UP) {
 
1735
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1736
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1737
        if(ret == -1){
 
1738
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
2408
1739
        }
2409
1740
      }
2410
 
      if(debug and (interfaces_to_take_down == NULL)){
2411
 
        fprintf_plus(stderr, "No interfaces needed to be taken"
2412
 
                     " down\n");
 
1741
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1742
      if(ret == -1){
 
1743
        perror("close");
 
1744
      }
 
1745
      /* Lower privileges permanently */
 
1746
      errno = 0;
 
1747
      ret = setuid(uid);
 
1748
      if(ret == -1){
 
1749
        perror("setuid");
2413
1750
      }
2414
1751
    }
2415
 
    
2416
 
    lower_privileges_permanently();
2417
1752
  }
2418
1753
  
2419
 
  free(interfaces_to_take_down);
2420
 
  free(interfaces_hooks);
2421
 
  
2422
 
  /* Removes the GPGME temp directory and all files inside */
 
1754
  /* Removes the temp directory used by GPGME */
2423
1755
  if(tempdir_created){
2424
 
    struct dirent **direntries = NULL;
2425
 
    struct dirent *direntry = NULL;
2426
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2427
 
                             alphasort);
2428
 
    if (numentries > 0){
2429
 
      for(int i = 0; i < numentries; i++){
2430
 
        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
        }
2431
1776
        char *fullname = NULL;
2432
1777
        ret = asprintf(&fullname, "%s/%s", tempdir,
2433
1778
                       direntry->d_name);
2434
1779
        if(ret < 0){
2435
 
          perror_plus("asprintf");
 
1780
          perror("asprintf");
2436
1781
          continue;
2437
1782
        }
2438
1783
        ret = remove(fullname);
2439
1784
        if(ret == -1){
2440
 
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
2441
 
                       strerror(errno));
 
1785
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1786
                  strerror(errno));
2442
1787
        }
2443
1788
        free(fullname);
2444
1789
      }
2445
 
    }
2446
 
 
2447
 
    /* need to clean even if 0 because man page doesn't specify */
2448
 
    free(direntries);
2449
 
    if (numentries == -1){
2450
 
      perror_plus("scandir");
 
1790
      closedir(d);
2451
1791
    }
2452
1792
    ret = rmdir(tempdir);
2453
1793
    if(ret == -1 and errno != ENOENT){
2454
 
      perror_plus("rmdir");
 
1794
      perror("rmdir");
2455
1795
    }
2456
1796
  }
2457
1797
  
2462
1802
                                            &old_sigterm_action,
2463
1803
                                            NULL));
2464
1804
    if(ret == -1){
2465
 
      perror_plus("sigaction");
 
1805
      perror("sigaction");
2466
1806
    }
2467
1807
    do {
2468
1808
      ret = raise(signal_received);
2469
1809
    } while(ret != 0 and errno == EINTR);
2470
1810
    if(ret != 0){
2471
 
      perror_plus("raise");
 
1811
      perror("raise");
2472
1812
      abort();
2473
1813
    }
2474
1814
    TEMP_FAILURE_RETRY(pause());