/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: 2014-07-25 23:44:04 UTC
  • mfrom: (723.1.7 python27)
  • Revision ID: teddy@recompile.se-20140725234404-m6c733af4i3zs0la
Merge from Python 2.7 branch.

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008-2014 Teddy Hogeborn
 
13
 * Copyright © 2008-2014 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
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
33
#ifndef _LARGEFILE_SOURCE
34
34
#define _LARGEFILE_SOURCE
35
 
#endif
 
35
#endif  /* not _LARGEFILE_SOURCE */
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif
 
38
#endif  /* not _FILE_OFFSET_BITS */
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror(), remove() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t */
 
43
                                   stdout, ferror() */
 
44
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
55
55
                                   opendir(), DIR */
56
56
#include <sys/stat.h>           /* open(), S_ISREG */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect() */
59
 
#include <fcntl.h>              /* open() */
 
58
                                   inet_pton(), connect(),
 
59
                                   getnameinfo() */
 
60
#include <fcntl.h>              /* open(), unlinkat() */
60
61
#include <dirent.h>             /* opendir(), struct dirent, readdir()
61
62
                                 */
62
63
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
63
64
                                   strtoimax() */
64
 
#include <assert.h>             /* assert() */
65
65
#include <errno.h>              /* perror(), errno,
66
66
                                   program_invocation_short_name */
67
67
#include <time.h>               /* nanosleep(), time(), sleep() */
73
73
                                */
74
74
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
75
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
                                   setgid(), pause(), _exit(),
 
77
                                   unlinkat() */
 
78
#include <arpa/inet.h>          /* inet_pton(), htons() */
78
79
#include <iso646.h>             /* not, or, and */
79
80
#include <argp.h>               /* struct argp_option, error_t, struct
80
81
                                   argp_state, struct argp,
85
86
                                   raise() */
86
87
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
87
88
                                   EX_NOHOST, EX_IOERR, EX_PROTOCOL */
 
89
#include <sys/wait.h>           /* waitpid(), WIFEXITED(),
 
90
                                   WEXITSTATUS(), WTERMSIG() */
 
91
#include <grp.h>                /* setgroups() */
 
92
#include <argz.h>               /* argz_add_sep(), argz_next(),
 
93
                                   argz_delete(), argz_append(),
 
94
                                   argz_stringify(), argz_add(),
 
95
                                   argz_count() */
 
96
#include <netdb.h>              /* getnameinfo(), NI_NUMERICHOST,
 
97
                                   EAI_SYSTEM, gai_strerror() */
88
98
 
89
99
#ifdef __linux__
90
100
#include <sys/klog.h>           /* klogctl() */
108
118
                                   init_gnutls_session(),
109
119
                                   GNUTLS_* */
110
120
#include <gnutls/openpgp.h>
111
 
                          /* gnutls_certificate_set_openpgp_key_file(),
112
 
                                   GNUTLS_OPENPGP_FMT_BASE64 */
 
121
                         /* gnutls_certificate_set_openpgp_key_file(),
 
122
                            GNUTLS_OPENPGP_FMT_BASE64 */
113
123
 
114
124
/* GPGME */
115
125
#include <gpgme.h>              /* All GPGME types, constants and
131
141
const char *argp_program_bug_address = "<mandos@recompile.se>";
132
142
static const char sys_class_net[] = "/sys/class/net";
133
143
char *connect_to = NULL;
 
144
const char *hookdir = HOOKDIR;
 
145
int hookdir_fd = -1;
 
146
uid_t uid = 65534;
 
147
gid_t gid = 65534;
134
148
 
135
149
/* Doubly linked list that need to be circularly linked when used */
136
150
typedef struct server{
137
151
  const char *ip;
138
 
  uint16_t port;
 
152
  in_port_t port;
139
153
  AvahiIfIndex if_index;
140
154
  int af;
141
155
  struct timespec last_seen;
145
159
 
146
160
/* Used for passing in values through the Avahi callback functions */
147
161
typedef struct {
148
 
  AvahiSimplePoll *simple_poll;
149
162
  AvahiServer *server;
150
163
  gnutls_certificate_credentials_t cred;
151
164
  unsigned int dh_bits;
153
166
  const char *priority;
154
167
  gpgme_ctx_t ctx;
155
168
  server *current_server;
 
169
  char *interfaces;
 
170
  size_t interfaces_size;
156
171
} mandos_context;
157
172
 
158
 
/* global context so signal handler can reach it*/
159
 
mandos_context mc = { .simple_poll = NULL, .server = NULL,
160
 
                      .dh_bits = 1024, .priority = "SECURE256"
161
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
162
 
                      .current_server = NULL };
 
173
/* global so signal handler can reach it*/
 
174
AvahiSimplePoll *simple_poll;
163
175
 
164
176
sig_atomic_t quit_now = 0;
165
177
int signal_received = 0;
166
178
 
167
179
/* Function to use when printing errors */
168
180
void perror_plus(const char *print_text){
 
181
  int e = errno;
169
182
  fprintf(stderr, "Mandos plugin %s: ",
170
183
          program_invocation_short_name);
 
184
  errno = e;
171
185
  perror(print_text);
172
186
}
173
187
 
 
188
__attribute__((format (gnu_printf, 2, 3), nonnull))
 
189
int fprintf_plus(FILE *stream, const char *format, ...){
 
190
  va_list ap;
 
191
  va_start (ap, format);
 
192
  
 
193
  TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ",
 
194
                             program_invocation_short_name));
 
195
  return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap));
 
196
}
 
197
 
174
198
/*
175
199
 * Make additional room in "buffer" for at least BUFFER_SIZE more
176
200
 * bytes. "buffer_capacity" is how much is currently allocated,
177
201
 * "buffer_length" is how much is already used.
178
202
 */
 
203
__attribute__((nonnull, warn_unused_result))
179
204
size_t incbuffer(char **buffer, size_t buffer_length,
180
 
                  size_t buffer_capacity){
 
205
                 size_t buffer_capacity){
181
206
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
182
 
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
183
 
    if(buffer == NULL){
 
207
    char *new_buf = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
208
    if(new_buf == NULL){
 
209
      int old_errno = errno;
 
210
      free(*buffer);
 
211
      errno = old_errno;
 
212
      *buffer = NULL;
184
213
      return 0;
185
214
    }
 
215
    *buffer = new_buf;
186
216
    buffer_capacity += BUFFER_SIZE;
187
217
  }
188
218
  return buffer_capacity;
189
219
}
190
220
 
191
221
/* Add server to set of servers to retry periodically */
192
 
int add_server(const char *ip, uint16_t port,
193
 
                 AvahiIfIndex if_index,
194
 
                 int af){
 
222
__attribute__((nonnull, warn_unused_result))
 
223
bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index,
 
224
                int af, server **current_server){
195
225
  int ret;
196
226
  server *new_server = malloc(sizeof(server));
197
227
  if(new_server == NULL){
198
228
    perror_plus("malloc");
199
 
    return -1;
 
229
    return false;
200
230
  }
201
231
  *new_server = (server){ .ip = strdup(ip),
202
 
                         .port = port,
203
 
                         .if_index = if_index,
204
 
                         .af = af };
 
232
                          .port = port,
 
233
                          .if_index = if_index,
 
234
                          .af = af };
205
235
  if(new_server->ip == NULL){
206
236
    perror_plus("strdup");
207
 
    return -1;
 
237
    free(new_server);
 
238
    return false;
 
239
  }
 
240
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
 
241
  if(ret == -1){
 
242
    perror_plus("clock_gettime");
 
243
#ifdef __GNUC__
 
244
#pragma GCC diagnostic push
 
245
#pragma GCC diagnostic ignored "-Wcast-qual"
 
246
#endif
 
247
    free((char *)(new_server->ip));
 
248
#ifdef __GNUC__
 
249
#pragma GCC diagnostic pop
 
250
#endif
 
251
    free(new_server);
 
252
    return false;
208
253
  }
209
254
  /* Special case of first server */
210
 
  if (mc.current_server == NULL){
 
255
  if(*current_server == NULL){
211
256
    new_server->next = new_server;
212
257
    new_server->prev = new_server;
213
 
    mc.current_server = new_server;
214
 
  /* Place the new server last in the list */
 
258
    *current_server = new_server;
215
259
  } else {
216
 
    new_server->next = mc.current_server;
217
 
    new_server->prev = mc.current_server->prev;
 
260
    /* Place the new server last in the list */
 
261
    new_server->next = *current_server;
 
262
    new_server->prev = (*current_server)->prev;
218
263
    new_server->prev->next = new_server;
219
 
    mc.current_server->prev = new_server;
220
 
  }
221
 
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
222
 
  if(ret == -1){
223
 
    perror_plus("clock_gettime");
224
 
    return -1;
225
 
  }
226
 
  return 0;
 
264
    (*current_server)->prev = new_server;
 
265
  }
 
266
  return true;
227
267
}
228
268
 
229
269
/* 
230
270
 * Initialize GPGME.
231
271
 */
232
 
static bool init_gpgme(const char *seckey,
233
 
                       const char *pubkey, const char *tempdir){
 
272
__attribute__((nonnull, warn_unused_result))
 
273
static bool init_gpgme(const char * const seckey,
 
274
                       const char * const pubkey,
 
275
                       const char * const tempdir,
 
276
                       mandos_context *mc){
234
277
  gpgme_error_t rc;
235
278
  gpgme_engine_info_t engine_info;
236
279
  
237
 
  
238
280
  /*
239
281
   * Helper function to insert pub and seckey to the engine keyring.
240
282
   */
241
 
  bool import_key(const char *filename){
 
283
  bool import_key(const char * const filename){
242
284
    int ret;
243
285
    int fd;
244
286
    gpgme_data_t pgp_data;
251
293
    
252
294
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
253
295
    if(rc != GPG_ERR_NO_ERROR){
254
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
255
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
296
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
297
                   gpgme_strsource(rc), gpgme_strerror(rc));
256
298
      return false;
257
299
    }
258
300
    
259
 
    rc = gpgme_op_import(mc.ctx, pgp_data);
 
301
    rc = gpgme_op_import(mc->ctx, pgp_data);
260
302
    if(rc != GPG_ERR_NO_ERROR){
261
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
262
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
303
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
304
                   gpgme_strsource(rc), gpgme_strerror(rc));
263
305
      return false;
264
306
    }
265
307
    
272
314
  }
273
315
  
274
316
  if(debug){
275
 
    fprintf(stderr, "Initializing GPGME\n");
 
317
    fprintf_plus(stderr, "Initializing GPGME\n");
276
318
  }
277
319
  
278
320
  /* Init GPGME */
279
321
  gpgme_check_version(NULL);
280
322
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
281
323
  if(rc != GPG_ERR_NO_ERROR){
282
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
283
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
324
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
325
                 gpgme_strsource(rc), gpgme_strerror(rc));
284
326
    return false;
285
327
  }
286
328
  
287
329
  /* Set GPGME home directory for the OpenPGP engine only */
288
330
  rc = gpgme_get_engine_info(&engine_info);
289
331
  if(rc != GPG_ERR_NO_ERROR){
290
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
291
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
332
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
333
                 gpgme_strsource(rc), gpgme_strerror(rc));
292
334
    return false;
293
335
  }
294
336
  while(engine_info != NULL){
300
342
    engine_info = engine_info->next;
301
343
  }
302
344
  if(engine_info == NULL){
303
 
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
 
345
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
 
346
                 tempdir);
304
347
    return false;
305
348
  }
306
349
  
307
350
  /* Create new GPGME "context" */
308
 
  rc = gpgme_new(&(mc.ctx));
 
351
  rc = gpgme_new(&(mc->ctx));
309
352
  if(rc != GPG_ERR_NO_ERROR){
310
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
311
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
353
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
354
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
 
355
                 gpgme_strerror(rc));
312
356
    return false;
313
357
  }
314
358
  
323
367
 * Decrypt OpenPGP data.
324
368
 * Returns -1 on error
325
369
 */
 
370
__attribute__((nonnull, warn_unused_result))
326
371
static ssize_t pgp_packet_decrypt(const char *cryptotext,
327
372
                                  size_t crypto_size,
328
 
                                  char **plaintext){
 
373
                                  char **plaintext,
 
374
                                  mandos_context *mc){
329
375
  gpgme_data_t dh_crypto, dh_plain;
330
376
  gpgme_error_t rc;
331
377
  ssize_t ret;
333
379
  ssize_t plaintext_length = 0;
334
380
  
335
381
  if(debug){
336
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
382
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
337
383
  }
338
384
  
339
385
  /* Create new GPGME data buffer from memory cryptotext */
340
386
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
341
387
                               0);
342
388
  if(rc != GPG_ERR_NO_ERROR){
343
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
344
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
389
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
390
                 gpgme_strsource(rc), gpgme_strerror(rc));
345
391
    return -1;
346
392
  }
347
393
  
348
394
  /* Create new empty GPGME data buffer for the plaintext */
349
395
  rc = gpgme_data_new(&dh_plain);
350
396
  if(rc != GPG_ERR_NO_ERROR){
351
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
352
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
397
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
 
398
                 "bad gpgme_data_new: %s: %s\n",
 
399
                 gpgme_strsource(rc), gpgme_strerror(rc));
353
400
    gpgme_data_release(dh_crypto);
354
401
    return -1;
355
402
  }
356
403
  
357
404
  /* Decrypt data from the cryptotext data buffer to the plaintext
358
405
     data buffer */
359
 
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
 
406
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
360
407
  if(rc != GPG_ERR_NO_ERROR){
361
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
362
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
408
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
409
                 gpgme_strsource(rc), gpgme_strerror(rc));
363
410
    plaintext_length = -1;
364
411
    if(debug){
365
412
      gpgme_decrypt_result_t result;
366
 
      result = gpgme_op_decrypt_result(mc.ctx);
 
413
      result = gpgme_op_decrypt_result(mc->ctx);
367
414
      if(result == NULL){
368
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
415
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
369
416
      } else {
370
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
371
 
                result->unsupported_algorithm);
372
 
        fprintf(stderr, "Wrong key usage: %u\n",
373
 
                result->wrong_key_usage);
 
417
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
 
418
                     result->unsupported_algorithm);
 
419
        fprintf_plus(stderr, "Wrong key usage: %u\n",
 
420
                     result->wrong_key_usage);
374
421
        if(result->file_name != NULL){
375
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
422
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
376
423
        }
377
424
        gpgme_recipient_t recipient;
378
425
        recipient = result->recipients;
379
426
        while(recipient != NULL){
380
 
          fprintf(stderr, "Public key algorithm: %s\n",
381
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
382
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
383
 
          fprintf(stderr, "Secret key available: %s\n",
384
 
                  recipient->status == GPG_ERR_NO_SECKEY
385
 
                  ? "No" : "Yes");
 
427
          fprintf_plus(stderr, "Public key algorithm: %s\n",
 
428
                       gpgme_pubkey_algo_name
 
429
                       (recipient->pubkey_algo));
 
430
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
 
431
          fprintf_plus(stderr, "Secret key available: %s\n",
 
432
                       recipient->status == GPG_ERR_NO_SECKEY
 
433
                       ? "No" : "Yes");
386
434
          recipient = recipient->next;
387
435
        }
388
436
      }
391
439
  }
392
440
  
393
441
  if(debug){
394
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
442
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
395
443
  }
396
444
  
397
445
  /* Seek back to the beginning of the GPGME plaintext data buffer */
404
452
  *plaintext = NULL;
405
453
  while(true){
406
454
    plaintext_capacity = incbuffer(plaintext,
407
 
                                      (size_t)plaintext_length,
408
 
                                      plaintext_capacity);
 
455
                                   (size_t)plaintext_length,
 
456
                                   plaintext_capacity);
409
457
    if(plaintext_capacity == 0){
410
 
        perror_plus("incbuffer");
411
 
        plaintext_length = -1;
412
 
        goto decrypt_end;
 
458
      perror_plus("incbuffer");
 
459
      plaintext_length = -1;
 
460
      goto decrypt_end;
413
461
    }
414
462
    
415
463
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
428
476
  }
429
477
  
430
478
  if(debug){
431
 
    fprintf(stderr, "Decrypted password is: ");
 
479
    fprintf_plus(stderr, "Decrypted password is: ");
432
480
    for(ssize_t i = 0; i < plaintext_length; i++){
433
481
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
434
482
    }
445
493
  return plaintext_length;
446
494
}
447
495
 
448
 
static const char * safer_gnutls_strerror(int value){
449
 
  const char *ret = gnutls_strerror(value); /* Spurious warning from
450
 
                                               -Wunreachable-code */
 
496
__attribute__((warn_unused_result))
 
497
static const char *safer_gnutls_strerror(int value){
 
498
  const char *ret = gnutls_strerror(value);
451
499
  if(ret == NULL)
452
500
    ret = "(unknown)";
453
501
  return ret;
454
502
}
455
503
 
456
504
/* GnuTLS log function callback */
 
505
__attribute__((nonnull))
457
506
static void debuggnutls(__attribute__((unused)) int level,
458
507
                        const char* string){
459
 
  fprintf(stderr, "GnuTLS: %s", string);
 
508
  fprintf_plus(stderr, "GnuTLS: %s", string);
460
509
}
461
510
 
 
511
__attribute__((nonnull, warn_unused_result))
462
512
static int init_gnutls_global(const char *pubkeyfilename,
463
 
                              const char *seckeyfilename){
 
513
                              const char *seckeyfilename,
 
514
                              mandos_context *mc){
464
515
  int ret;
465
516
  
466
517
  if(debug){
467
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
518
    fprintf_plus(stderr, "Initializing GnuTLS\n");
468
519
  }
469
520
  
470
521
  ret = gnutls_global_init();
471
522
  if(ret != GNUTLS_E_SUCCESS){
472
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
473
 
            safer_gnutls_strerror(ret));
 
523
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
524
                 safer_gnutls_strerror(ret));
474
525
    return -1;
475
526
  }
476
527
  
483
534
  }
484
535
  
485
536
  /* OpenPGP credentials */
486
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
537
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
487
538
  if(ret != GNUTLS_E_SUCCESS){
488
 
    fprintf(stderr, "GnuTLS memory error: %s\n",
489
 
            safer_gnutls_strerror(ret));
 
539
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
540
                 safer_gnutls_strerror(ret));
490
541
    gnutls_global_deinit();
491
542
    return -1;
492
543
  }
493
544
  
494
545
  if(debug){
495
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
496
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
497
 
            seckeyfilename);
 
546
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
 
547
                 " secret key %s as GnuTLS credentials\n",
 
548
                 pubkeyfilename,
 
549
                 seckeyfilename);
498
550
  }
499
551
  
500
552
  ret = gnutls_certificate_set_openpgp_key_file
501
 
    (mc.cred, pubkeyfilename, seckeyfilename,
 
553
    (mc->cred, pubkeyfilename, seckeyfilename,
502
554
     GNUTLS_OPENPGP_FMT_BASE64);
503
555
  if(ret != GNUTLS_E_SUCCESS){
504
 
    fprintf(stderr,
505
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
506
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
507
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
508
 
            safer_gnutls_strerror(ret));
 
556
    fprintf_plus(stderr,
 
557
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
 
558
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
559
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
 
560
                 safer_gnutls_strerror(ret));
509
561
    goto globalfail;
510
562
  }
511
563
  
512
564
  /* GnuTLS server initialization */
513
 
  ret = gnutls_dh_params_init(&mc.dh_params);
 
565
  ret = gnutls_dh_params_init(&mc->dh_params);
514
566
  if(ret != GNUTLS_E_SUCCESS){
515
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
516
 
            " %s\n", safer_gnutls_strerror(ret));
 
567
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
568
                 " initialization: %s\n",
 
569
                 safer_gnutls_strerror(ret));
517
570
    goto globalfail;
518
571
  }
519
 
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
572
  ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
520
573
  if(ret != GNUTLS_E_SUCCESS){
521
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
522
 
            safer_gnutls_strerror(ret));
 
574
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
575
                 safer_gnutls_strerror(ret));
523
576
    goto globalfail;
524
577
  }
525
578
  
526
 
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
 
579
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
527
580
  
528
581
  return 0;
529
582
  
530
583
 globalfail:
531
584
  
532
 
  gnutls_certificate_free_credentials(mc.cred);
 
585
  gnutls_certificate_free_credentials(mc->cred);
533
586
  gnutls_global_deinit();
534
 
  gnutls_dh_params_deinit(mc.dh_params);
 
587
  gnutls_dh_params_deinit(mc->dh_params);
535
588
  return -1;
536
589
}
537
590
 
538
 
static int init_gnutls_session(gnutls_session_t *session){
 
591
__attribute__((nonnull, warn_unused_result))
 
592
static int init_gnutls_session(gnutls_session_t *session,
 
593
                               mandos_context *mc){
539
594
  int ret;
540
595
  /* GnuTLS session creation */
541
596
  do {
545
600
    }
546
601
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
547
602
  if(ret != GNUTLS_E_SUCCESS){
548
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
549
 
            safer_gnutls_strerror(ret));
 
603
    fprintf_plus(stderr,
 
604
                 "Error in GnuTLS session initialization: %s\n",
 
605
                 safer_gnutls_strerror(ret));
550
606
  }
551
607
  
552
608
  {
553
609
    const char *err;
554
610
    do {
555
 
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
 
611
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
556
612
      if(quit_now){
557
613
        gnutls_deinit(*session);
558
614
        return -1;
559
615
      }
560
616
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
561
617
    if(ret != GNUTLS_E_SUCCESS){
562
 
      fprintf(stderr, "Syntax error at: %s\n", err);
563
 
      fprintf(stderr, "GnuTLS error: %s\n",
564
 
              safer_gnutls_strerror(ret));
 
618
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
 
619
      fprintf_plus(stderr, "GnuTLS error: %s\n",
 
620
                   safer_gnutls_strerror(ret));
565
621
      gnutls_deinit(*session);
566
622
      return -1;
567
623
    }
569
625
  
570
626
  do {
571
627
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
572
 
                                 mc.cred);
 
628
                                 mc->cred);
573
629
    if(quit_now){
574
630
      gnutls_deinit(*session);
575
631
      return -1;
576
632
    }
577
633
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
578
634
  if(ret != GNUTLS_E_SUCCESS){
579
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
580
 
            safer_gnutls_strerror(ret));
 
635
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
636
                 safer_gnutls_strerror(ret));
581
637
    gnutls_deinit(*session);
582
638
    return -1;
583
639
  }
585
641
  /* ignore client certificate if any. */
586
642
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
587
643
  
588
 
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
644
  gnutls_dh_set_prime_bits(*session, mc->dh_bits);
589
645
  
590
646
  return 0;
591
647
}
595
651
                      __attribute__((unused)) const char *txt){}
596
652
 
597
653
/* Called when a Mandos server is found */
598
 
static int start_mandos_communication(const char *ip, uint16_t port,
 
654
__attribute__((nonnull, warn_unused_result))
 
655
static int start_mandos_communication(const char *ip, in_port_t port,
599
656
                                      AvahiIfIndex if_index,
600
 
                                      int af){
 
657
                                      int af, mandos_context *mc){
601
658
  int ret, tcp_sd = -1;
602
659
  ssize_t sret;
603
 
  union {
604
 
    struct sockaddr_in in;
605
 
    struct sockaddr_in6 in6;
606
 
  } to;
 
660
  struct sockaddr_storage to;
607
661
  char *buffer = NULL;
608
662
  char *decrypted_buffer = NULL;
609
663
  size_t buffer_length = 0;
628
682
    pf = PF_INET;
629
683
    break;
630
684
  default:
631
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
685
    fprintf_plus(stderr, "Bad address family: %d\n", af);
632
686
    errno = EINVAL;
633
687
    return -1;
634
688
  }
635
689
  
636
 
  ret = init_gnutls_session(&session);
 
690
  /* If the interface is specified and we have a list of interfaces */
 
691
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
 
692
    /* Check if the interface is one of the interfaces we are using */
 
693
    bool match = false;
 
694
    {
 
695
      char *interface = NULL;
 
696
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
 
697
                                 interface))){
 
698
        if(if_nametoindex(interface) == (unsigned int)if_index){
 
699
          match = true;
 
700
          break;
 
701
        }
 
702
      }
 
703
    }
 
704
    if(not match){
 
705
      /* This interface does not match any in the list, so we don't
 
706
         connect to the server */
 
707
      if(debug){
 
708
        char interface[IF_NAMESIZE];
 
709
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
 
710
          perror_plus("if_indextoname");
 
711
        } else {
 
712
          fprintf_plus(stderr, "Skipping server on non-used interface"
 
713
                       " \"%s\"\n",
 
714
                       if_indextoname((unsigned int)if_index,
 
715
                                      interface));
 
716
        }
 
717
      }
 
718
      return -1;
 
719
    }
 
720
  }
 
721
  
 
722
  ret = init_gnutls_session(&session, mc);
637
723
  if(ret != 0){
638
724
    return -1;
639
725
  }
640
726
  
641
727
  if(debug){
642
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
643
 
            "\n", ip, port);
 
728
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
729
                 PRIuMAX "\n", ip, (uintmax_t)port);
644
730
  }
645
731
  
646
732
  tcp_sd = socket(pf, SOCK_STREAM, 0);
658
744
  
659
745
  memset(&to, 0, sizeof(to));
660
746
  if(af == AF_INET6){
661
 
    to.in6.sin6_family = (sa_family_t)af;
662
 
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
 
747
    ((struct sockaddr_in6 *)&to)->sin6_family = (sa_family_t)af;
 
748
    ret = inet_pton(af, ip, &((struct sockaddr_in6 *)&to)->sin6_addr);
663
749
  } else {                      /* IPv4 */
664
 
    to.in.sin_family = (sa_family_t)af;
665
 
    ret = inet_pton(af, ip, &to.in.sin_addr);
 
750
    ((struct sockaddr_in *)&to)->sin_family = (sa_family_t)af;
 
751
    ret = inet_pton(af, ip, &((struct sockaddr_in *)&to)->sin_addr);
666
752
  }
667
753
  if(ret < 0 ){
668
754
    int e = errno;
672
758
  }
673
759
  if(ret == 0){
674
760
    int e = errno;
675
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
761
    fprintf_plus(stderr, "Bad address: %s\n", ip);
676
762
    errno = e;
677
763
    goto mandos_end;
678
764
  }
679
765
  if(af == AF_INET6){
680
 
    to.in6.sin6_port = htons(port); /* Spurious warnings from
681
 
                                       -Wconversion and
682
 
                                       -Wunreachable-code */
683
 
    
684
 
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
685
 
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
686
 
                              -Wunreachable-code*/
 
766
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
 
767
    if(IN6_IS_ADDR_LINKLOCAL
 
768
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
687
769
      if(if_index == AVAHI_IF_UNSPEC){
688
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
689
 
                " without a network interface\n");
 
770
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
771
                     " incomplete without a network interface\n");
690
772
        errno = EINVAL;
691
773
        goto mandos_end;
692
774
      }
693
775
      /* Set the network interface number as scope */
694
 
      to.in6.sin6_scope_id = (uint32_t)if_index;
 
776
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
695
777
    }
696
778
  } else {
697
 
    to.in.sin_port = htons(port); /* Spurious warnings from
698
 
                                     -Wconversion and
699
 
                                     -Wunreachable-code */
 
779
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
700
780
  }
701
781
  
702
782
  if(quit_now){
710
790
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
711
791
        perror_plus("if_indextoname");
712
792
      } else {
713
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
714
 
                ip, interface, port);
 
793
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
 
794
                     "\n", ip, interface, (uintmax_t)port);
715
795
      }
716
796
    } else {
717
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
718
 
              port);
 
797
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
 
798
                   ip, (uintmax_t)port);
719
799
    }
720
800
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
721
801
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
722
 
    const char *pcret;
723
802
    if(af == AF_INET6){
724
 
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
725
 
                        sizeof(addrstr));
 
803
      ret = getnameinfo((struct sockaddr *)&to,
 
804
                        sizeof(struct sockaddr_in6),
 
805
                        addrstr, sizeof(addrstr), NULL, 0,
 
806
                        NI_NUMERICHOST);
726
807
    } else {
727
 
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
728
 
                        sizeof(addrstr));
 
808
      ret = getnameinfo((struct sockaddr *)&to,
 
809
                        sizeof(struct sockaddr_in),
 
810
                        addrstr, sizeof(addrstr), NULL, 0,
 
811
                        NI_NUMERICHOST);
729
812
    }
730
 
    if(pcret == NULL){
731
 
      perror_plus("inet_ntop");
732
 
    } else {
733
 
      if(strcmp(addrstr, ip) != 0){
734
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
735
 
      }
 
813
    if(ret == EAI_SYSTEM){
 
814
      perror_plus("getnameinfo");
 
815
    } else if(ret != 0) {
 
816
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
 
817
    } else if(strcmp(addrstr, ip) != 0){
 
818
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
736
819
    }
737
820
  }
738
821
  
742
825
  }
743
826
  
744
827
  if(af == AF_INET6){
745
 
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
828
    ret = connect(tcp_sd, (struct sockaddr *)&to,
 
829
                  sizeof(struct sockaddr_in6));
746
830
  } else {
747
 
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
831
    ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
 
832
                  sizeof(struct sockaddr_in));
748
833
  }
749
834
  if(ret < 0){
750
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
835
    if((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
751
836
      int e = errno;
752
837
      perror_plus("connect");
753
838
      errno = e;
765
850
  while(true){
766
851
    size_t out_size = strlen(out);
767
852
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
768
 
                                   out_size - written));
 
853
                                        out_size - written));
769
854
    if(ret == -1){
770
855
      int e = errno;
771
856
      perror_plus("write");
791
876
  }
792
877
  
793
878
  if(debug){
794
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
879
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
795
880
  }
796
881
  
797
882
  if(quit_now){
799
884
    goto mandos_end;
800
885
  }
801
886
  
802
 
  /* Spurious warning from -Wint-to-pointer-cast */
803
 
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
 
887
  /* This casting via intptr_t is to eliminate warning about casting
 
888
     an int to a pointer type.  This is exactly how the GnuTLS Guile
 
889
     function "set-session-transport-fd!" does it. */
 
890
  gnutls_transport_set_ptr(session,
 
891
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
804
892
  
805
893
  if(quit_now){
806
894
    errno = EINTR;
817
905
  
818
906
  if(ret != GNUTLS_E_SUCCESS){
819
907
    if(debug){
820
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
908
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
821
909
      gnutls_perror(ret);
822
910
    }
823
911
    errno = EPROTO;
827
915
  /* Read OpenPGP packet that contains the wanted password */
828
916
  
829
917
  if(debug){
830
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
831
 
            ip);
 
918
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
919
                 " %s\n", ip);
832
920
  }
833
921
  
834
922
  while(true){
839
927
    }
840
928
    
841
929
    buffer_capacity = incbuffer(&buffer, buffer_length,
842
 
                                   buffer_capacity);
 
930
                                buffer_capacity);
843
931
    if(buffer_capacity == 0){
844
932
      int e = errno;
845
933
      perror_plus("incbuffer");
872
960
          }
873
961
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
874
962
        if(ret < 0){
875
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
963
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
964
                       "***\n");
876
965
          gnutls_perror(ret);
877
966
          errno = EPROTO;
878
967
          goto mandos_end;
879
968
        }
880
969
        break;
881
970
      default:
882
 
        fprintf(stderr, "Unknown error while reading data from"
883
 
                " encrypted session with Mandos server\n");
 
971
        fprintf_plus(stderr, "Unknown error while reading data from"
 
972
                     " encrypted session with Mandos server\n");
884
973
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
885
974
        errno = EIO;
886
975
        goto mandos_end;
891
980
  }
892
981
  
893
982
  if(debug){
894
 
    fprintf(stderr, "Closing TLS session\n");
 
983
    fprintf_plus(stderr, "Closing TLS session\n");
895
984
  }
896
985
  
897
986
  if(quit_now){
909
998
  
910
999
  if(buffer_length > 0){
911
1000
    ssize_t decrypted_buffer_size;
912
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
913
 
                                               buffer_length,
914
 
                                               &decrypted_buffer);
 
1001
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
1002
                                               &decrypted_buffer, mc);
915
1003
    if(decrypted_buffer_size >= 0){
916
1004
      
917
1005
      written = 0;
927
1015
        if(ret == 0 and ferror(stdout)){
928
1016
          int e = errno;
929
1017
          if(debug){
930
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
931
 
                    strerror(errno));
 
1018
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
1019
                         strerror(errno));
932
1020
          }
933
1021
          errno = e;
934
1022
          goto mandos_end;
965
1053
  return retval;
966
1054
}
967
1055
 
 
1056
__attribute__((nonnull))
968
1057
static void resolve_callback(AvahiSServiceResolver *r,
969
1058
                             AvahiIfIndex interface,
970
1059
                             AvahiProtocol proto,
978
1067
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
979
1068
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
980
1069
                             flags,
981
 
                             AVAHI_GCC_UNUSED void* userdata){
982
 
  assert(r);
 
1070
                             void *mc){
 
1071
  if(r == NULL){
 
1072
    return;
 
1073
  }
983
1074
  
984
1075
  /* Called whenever a service has been resolved successfully or
985
1076
     timed out */
986
1077
  
987
1078
  if(quit_now){
 
1079
    avahi_s_service_resolver_free(r);
988
1080
    return;
989
1081
  }
990
1082
  
991
1083
  switch(event){
992
1084
  default:
993
1085
  case AVAHI_RESOLVER_FAILURE:
994
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
995
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
996
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1086
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
 
1087
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
 
1088
                 domain,
 
1089
                 avahi_strerror(avahi_server_errno
 
1090
                                (((mandos_context*)mc)->server)));
997
1091
    break;
998
1092
    
999
1093
  case AVAHI_RESOLVER_FOUND:
1001
1095
      char ip[AVAHI_ADDRESS_STR_MAX];
1002
1096
      avahi_address_snprint(ip, sizeof(ip), address);
1003
1097
      if(debug){
1004
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1005
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1006
 
                ip, (intmax_t)interface, port);
 
1098
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1099
                     PRIdMAX ") on port %" PRIu16 "\n", name,
 
1100
                     host_name, ip, (intmax_t)interface, port);
1007
1101
      }
1008
 
      int ret = start_mandos_communication(ip, port, interface,
1009
 
                                           avahi_proto_to_af(proto));
 
1102
      int ret = start_mandos_communication(ip, (in_port_t)port,
 
1103
                                           interface,
 
1104
                                           avahi_proto_to_af(proto),
 
1105
                                           mc);
1010
1106
      if(ret == 0){
1011
 
        avahi_simple_poll_quit(mc.simple_poll);
 
1107
        avahi_simple_poll_quit(simple_poll);
1012
1108
      } else {
1013
 
        ret = add_server(ip, port, interface,
1014
 
                         avahi_proto_to_af(proto));
 
1109
        if(not add_server(ip, (in_port_t)port, interface,
 
1110
                          avahi_proto_to_af(proto),
 
1111
                          &((mandos_context*)mc)->current_server)){
 
1112
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
 
1113
                       " list\n", name);
 
1114
        }
1015
1115
      }
1016
1116
    }
1017
1117
  }
1027
1127
                            const char *domain,
1028
1128
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1029
1129
                            flags,
1030
 
                            AVAHI_GCC_UNUSED void* userdata){
1031
 
  assert(b);
 
1130
                            void *mc){
 
1131
  if(b == NULL){
 
1132
    return;
 
1133
  }
1032
1134
  
1033
1135
  /* Called whenever a new services becomes available on the LAN or
1034
1136
     is removed from the LAN */
1041
1143
  default:
1042
1144
  case AVAHI_BROWSER_FAILURE:
1043
1145
    
1044
 
    fprintf(stderr, "(Avahi browser) %s\n",
1045
 
            avahi_strerror(avahi_server_errno(mc.server)));
1046
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1146
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1147
                 avahi_strerror(avahi_server_errno
 
1148
                                (((mandos_context*)mc)->server)));
 
1149
    avahi_simple_poll_quit(simple_poll);
1047
1150
    return;
1048
1151
    
1049
1152
  case AVAHI_BROWSER_NEW:
1052
1155
       the callback function is called the Avahi server will free the
1053
1156
       resolver for us. */
1054
1157
    
1055
 
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1056
 
                                    name, type, domain, protocol, 0,
1057
 
                                    resolve_callback, NULL) == NULL)
1058
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1059
 
              name, avahi_strerror(avahi_server_errno(mc.server)));
 
1158
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
 
1159
                                    interface, protocol, name, type,
 
1160
                                    domain, protocol, 0,
 
1161
                                    resolve_callback, mc) == NULL)
 
1162
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
 
1163
                   " %s\n", name,
 
1164
                   avahi_strerror(avahi_server_errno
 
1165
                                  (((mandos_context*)mc)->server)));
1060
1166
    break;
1061
1167
    
1062
1168
  case AVAHI_BROWSER_REMOVE:
1065
1171
  case AVAHI_BROWSER_ALL_FOR_NOW:
1066
1172
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1067
1173
    if(debug){
1068
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1174
      fprintf_plus(stderr, "No Mandos server found, still"
 
1175
                   " searching...\n");
1069
1176
    }
1070
1177
    break;
1071
1178
  }
1080
1187
  signal_received = sig;
1081
1188
  int old_errno = errno;
1082
1189
  /* set main loop to exit */
1083
 
  if(mc.simple_poll != NULL){
1084
 
    avahi_simple_poll_quit(mc.simple_poll);
 
1190
  if(simple_poll != NULL){
 
1191
    avahi_simple_poll_quit(simple_poll);
1085
1192
  }
1086
1193
  errno = old_errno;
1087
1194
}
1088
1195
 
 
1196
__attribute__((nonnull, warn_unused_result))
1089
1197
bool get_flags(const char *ifname, struct ifreq *ifr){
1090
1198
  int ret;
 
1199
  error_t ret_errno;
1091
1200
  
1092
1201
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1093
1202
  if(s < 0){
 
1203
    ret_errno = errno;
1094
1204
    perror_plus("socket");
 
1205
    errno = ret_errno;
1095
1206
    return false;
1096
1207
  }
1097
1208
  strcpy(ifr->ifr_name, ifname);
1098
1209
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1099
1210
  if(ret == -1){
1100
1211
    if(debug){
 
1212
      ret_errno = errno;
1101
1213
      perror_plus("ioctl SIOCGIFFLAGS");
 
1214
      errno = ret_errno;
1102
1215
    }
1103
1216
    return false;
1104
1217
  }
1105
1218
  return true;
1106
1219
}
1107
1220
 
 
1221
__attribute__((nonnull, warn_unused_result))
1108
1222
bool good_flags(const char *ifname, const struct ifreq *ifr){
1109
1223
  
1110
1224
  /* Reject the loopback device */
1111
1225
  if(ifr->ifr_flags & IFF_LOOPBACK){
1112
1226
    if(debug){
1113
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1114
 
              ifname);
 
1227
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1228
                   ifname);
1115
1229
    }
1116
1230
    return false;
1117
1231
  }
1118
1232
  /* Accept point-to-point devices only if connect_to is specified */
1119
1233
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1120
1234
    if(debug){
1121
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1122
 
              ifname);
 
1235
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1236
                   " \"%s\"\n", ifname);
1123
1237
    }
1124
1238
    return true;
1125
1239
  }
1126
1240
  /* Otherwise, reject non-broadcast-capable devices */
1127
1241
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
1128
1242
    if(debug){
1129
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1130
 
              ifname);
 
1243
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
 
1244
                   " \"%s\"\n", ifname);
1131
1245
    }
1132
1246
    return false;
1133
1247
  }
1134
1248
  /* Reject non-ARP interfaces (including dummy interfaces) */
1135
1249
  if(ifr->ifr_flags & IFF_NOARP){
1136
1250
    if(debug){
1137
 
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n", ifname);
 
1251
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1252
                   ifname);
1138
1253
    }
1139
1254
    return false;
1140
1255
  }
1141
1256
  
1142
1257
  /* Accept this device */
1143
1258
  if(debug){
1144
 
    fprintf(stderr, "Interface \"%s\" is good\n", ifname);
 
1259
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1145
1260
  }
1146
1261
  return true;
1147
1262
}
1151
1266
 * corresponds to an acceptable network device.
1152
1267
 * (This function is passed to scandir(3) as a filter function.)
1153
1268
 */
 
1269
__attribute__((nonnull, warn_unused_result))
1154
1270
int good_interface(const struct dirent *if_entry){
1155
1271
  if(if_entry->d_name[0] == '.'){
1156
1272
    return 0;
1159
1275
  struct ifreq ifr;
1160
1276
  if(not get_flags(if_entry->d_name, &ifr)){
1161
1277
    if(debug){
1162
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1163
 
              if_entry->d_name);
1164
 
    }
1165
 
    return 0;
1166
 
  }
1167
 
  
1168
 
  if(not good_flags(if_entry->d_name, &ifr)){
1169
 
    return 0;
1170
 
  }
1171
 
  return 1;
1172
 
}
1173
 
 
1174
 
/* 
1175
 
 * This function determines if a directory entry in /sys/class/net
1176
 
 * corresponds to an acceptable network device which is up.
1177
 
 * (This function is passed to scandir(3) as a filter function.)
1178
 
 */
1179
 
int up_interface(const struct dirent *if_entry){
1180
 
  if(if_entry->d_name[0] == '.'){
1181
 
    return 0;
1182
 
  }
1183
 
  
1184
 
  struct ifreq ifr;
1185
 
  if(not get_flags(if_entry->d_name, &ifr)){
1186
 
    if(debug){
1187
 
      fprintf(stderr, "Failed to get flags for interface \"%s\"\n",
1188
 
              if_entry->d_name);
1189
 
    }
1190
 
    return 0;
1191
 
  }
1192
 
  
1193
 
  /* Reject down interfaces */
1194
 
  if(not (ifr.ifr_flags & IFF_UP)){
1195
 
    if(debug){
1196
 
      fprintf(stderr, "Rejecting down interface \"%s\"\n",
1197
 
              if_entry->d_name);
1198
 
    }
1199
 
    return 0;
1200
 
  }
1201
 
  
1202
 
  /* Reject non-running interfaces */
1203
 
  if(not (ifr.ifr_flags & IFF_RUNNING)){
1204
 
    if(debug){
1205
 
      fprintf(stderr, "Rejecting non-running interface \"%s\"\n",
1206
 
              if_entry->d_name);
1207
 
    }
1208
 
    return 0;
1209
 
  }
1210
 
  
1211
 
  if(not good_flags(if_entry->d_name, &ifr)){
1212
 
    return 0;
1213
 
  }
1214
 
  return 1;
1215
 
}
1216
 
 
 
1278
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1279
                   "\"%s\"\n", if_entry->d_name);
 
1280
    }
 
1281
    return 0;
 
1282
  }
 
1283
  
 
1284
  if(not good_flags(if_entry->d_name, &ifr)){
 
1285
    return 0;
 
1286
  }
 
1287
  return 1;
 
1288
}
 
1289
 
 
1290
/* 
 
1291
 * This function determines if a network interface is up.
 
1292
 */
 
1293
__attribute__((nonnull, warn_unused_result))
 
1294
bool interface_is_up(const char *interface){
 
1295
  struct ifreq ifr;
 
1296
  if(not get_flags(interface, &ifr)){
 
1297
    if(debug){
 
1298
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1299
                   "\"%s\"\n", interface);
 
1300
    }
 
1301
    return false;
 
1302
  }
 
1303
  
 
1304
  return (bool)(ifr.ifr_flags & IFF_UP);
 
1305
}
 
1306
 
 
1307
/* 
 
1308
 * This function determines if a network interface is running
 
1309
 */
 
1310
__attribute__((nonnull, warn_unused_result))
 
1311
bool interface_is_running(const char *interface){
 
1312
  struct ifreq ifr;
 
1313
  if(not get_flags(interface, &ifr)){
 
1314
    if(debug){
 
1315
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1316
                   "\"%s\"\n", interface);
 
1317
    }
 
1318
    return false;
 
1319
  }
 
1320
  
 
1321
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
 
1322
}
 
1323
 
 
1324
__attribute__((nonnull, pure, warn_unused_result))
1217
1325
int notdotentries(const struct dirent *direntry){
1218
1326
  /* Skip "." and ".." */
1219
1327
  if(direntry->d_name[0] == '.'
1226
1334
}
1227
1335
 
1228
1336
/* Is this directory entry a runnable program? */
 
1337
__attribute__((nonnull, warn_unused_result))
1229
1338
int runnable_hook(const struct dirent *direntry){
1230
1339
  int ret;
 
1340
  size_t sret;
1231
1341
  struct stat st;
1232
1342
  
1233
1343
  if((direntry->d_name)[0] == '\0'){
1235
1345
    return 0;
1236
1346
  }
1237
1347
  
1238
 
  /* Save pointer to last character */
1239
 
  char *end = strchr(direntry->d_name, '\0')-1;
1240
 
  
1241
 
  if(*end == '~'){
1242
 
    /* Backup name~ */
1243
 
    return 0;
1244
 
  }
1245
 
  
1246
 
  if(((direntry->d_name)[0] == '#')
1247
 
     and (*end == '#')){
1248
 
    /* Temporary #name# */
1249
 
    return 0;
1250
 
  }
1251
 
  
1252
 
  /* XXX more rules here */
1253
 
  
1254
 
  ret = stat(direntry->d_name, &st);
 
1348
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
 
1349
                "abcdefghijklmnopqrstuvwxyz"
 
1350
                "0123456789"
 
1351
                "_.-");
 
1352
  if((direntry->d_name)[sret] != '\0'){
 
1353
    /* Contains non-allowed characters */
 
1354
    if(debug){
 
1355
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
 
1356
                   direntry->d_name);
 
1357
    }
 
1358
    return 0;
 
1359
  }
 
1360
  
 
1361
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1255
1362
  if(ret == -1){
1256
1363
    if(debug){
1257
 
      perror_plus("Could not stat plugin");
 
1364
      perror_plus("Could not stat hook");
1258
1365
    }
1259
1366
    return 0;
1260
1367
  }
1261
1368
  if(not (S_ISREG(st.st_mode))){
1262
1369
    /* Not a regular file */
 
1370
    if(debug){
 
1371
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
 
1372
                   direntry->d_name);
 
1373
    }
1263
1374
    return 0;
1264
1375
  }
1265
1376
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1266
1377
    /* Not executable */
 
1378
    if(debug){
 
1379
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
 
1380
                   direntry->d_name);
 
1381
    }
1267
1382
    return 0;
1268
1383
  }
 
1384
  if(debug){
 
1385
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
 
1386
                 direntry->d_name);
 
1387
  }
1269
1388
  return 1;
1270
1389
}
1271
1390
 
1272
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
 
1391
__attribute__((nonnull, warn_unused_result))
 
1392
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
 
1393
                            mandos_context *mc){
1273
1394
  int ret;
1274
1395
  struct timespec now;
1275
1396
  struct timespec waited_time;
1276
1397
  intmax_t block_time;
1277
1398
  
1278
1399
  while(true){
1279
 
    if(mc.current_server == NULL){
1280
 
      if (debug){
1281
 
        fprintf(stderr,
1282
 
                "Wait until first server is found. No timeout!\n");
 
1400
    if(mc->current_server == NULL){
 
1401
      if(debug){
 
1402
        fprintf_plus(stderr, "Wait until first server is found."
 
1403
                     " No timeout!\n");
1283
1404
      }
1284
1405
      ret = avahi_simple_poll_iterate(s, -1);
1285
1406
    } else {
1286
 
      if (debug){
1287
 
        fprintf(stderr, "Check current_server if we should run it,"
1288
 
                " or wait\n");
 
1407
      if(debug){
 
1408
        fprintf_plus(stderr, "Check current_server if we should run"
 
1409
                     " it, or wait\n");
1289
1410
      }
1290
1411
      /* the current time */
1291
1412
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1296
1417
      /* Calculating in ms how long time between now and server
1297
1418
         who we visted longest time ago. Now - last seen.  */
1298
1419
      waited_time.tv_sec = (now.tv_sec
1299
 
                            - mc.current_server->last_seen.tv_sec);
 
1420
                            - mc->current_server->last_seen.tv_sec);
1300
1421
      waited_time.tv_nsec = (now.tv_nsec
1301
 
                             - mc.current_server->last_seen.tv_nsec);
 
1422
                             - mc->current_server->last_seen.tv_nsec);
1302
1423
      /* total time is 10s/10,000ms.
1303
1424
         Converting to s from ms by dividing by 1,000,
1304
1425
         and ns to ms by dividing by 1,000,000. */
1306
1427
                     - ((intmax_t)waited_time.tv_sec * 1000))
1307
1428
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1308
1429
      
1309
 
      if (debug){
1310
 
        fprintf(stderr, "Blocking for %" PRIdMAX " ms\n", block_time);
 
1430
      if(debug){
 
1431
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
 
1432
                     block_time);
1311
1433
      }
1312
1434
      
1313
1435
      if(block_time <= 0){
1314
 
        ret = start_mandos_communication(mc.current_server->ip,
1315
 
                                         mc.current_server->port,
1316
 
                                         mc.current_server->if_index,
1317
 
                                         mc.current_server->af);
 
1436
        ret = start_mandos_communication(mc->current_server->ip,
 
1437
                                         mc->current_server->port,
 
1438
                                         mc->current_server->if_index,
 
1439
                                         mc->current_server->af, mc);
1318
1440
        if(ret == 0){
1319
 
          avahi_simple_poll_quit(mc.simple_poll);
 
1441
          avahi_simple_poll_quit(s);
1320
1442
          return 0;
1321
1443
        }
1322
1444
        ret = clock_gettime(CLOCK_MONOTONIC,
1323
 
                            &mc.current_server->last_seen);
 
1445
                            &mc->current_server->last_seen);
1324
1446
        if(ret == -1){
1325
1447
          perror_plus("clock_gettime");
1326
1448
          return -1;
1327
1449
        }
1328
 
        mc.current_server = mc.current_server->next;
 
1450
        mc->current_server = mc->current_server->next;
1329
1451
        block_time = 0;         /* Call avahi to find new Mandos
1330
1452
                                   servers, but don't block */
1331
1453
      }
1333
1455
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1334
1456
    }
1335
1457
    if(ret != 0){
1336
 
      if (ret > 0 or errno != EINTR) {
 
1458
      if(ret > 0 or errno != EINTR){
1337
1459
        return (ret != 1) ? ret : 0;
1338
1460
      }
1339
1461
    }
1340
1462
  }
1341
1463
}
1342
1464
 
 
1465
/* Set effective uid to 0, return errno */
 
1466
__attribute__((warn_unused_result))
 
1467
error_t raise_privileges(void){
 
1468
  error_t old_errno = errno;
 
1469
  error_t ret_errno = 0;
 
1470
  if(seteuid(0) == -1){
 
1471
    ret_errno = errno;
 
1472
  }
 
1473
  errno = old_errno;
 
1474
  return ret_errno;
 
1475
}
 
1476
 
 
1477
/* Set effective and real user ID to 0.  Return errno. */
 
1478
__attribute__((warn_unused_result))
 
1479
error_t raise_privileges_permanently(void){
 
1480
  error_t old_errno = errno;
 
1481
  error_t ret_errno = raise_privileges();
 
1482
  if(ret_errno != 0){
 
1483
    errno = old_errno;
 
1484
    return ret_errno;
 
1485
  }
 
1486
  if(setuid(0) == -1){
 
1487
    ret_errno = errno;
 
1488
  }
 
1489
  errno = old_errno;
 
1490
  return ret_errno;
 
1491
}
 
1492
 
 
1493
/* Set effective user ID to unprivileged saved user ID */
 
1494
__attribute__((warn_unused_result))
 
1495
error_t lower_privileges(void){
 
1496
  error_t old_errno = errno;
 
1497
  error_t ret_errno = 0;
 
1498
  if(seteuid(uid) == -1){
 
1499
    ret_errno = errno;
 
1500
  }
 
1501
  errno = old_errno;
 
1502
  return ret_errno;
 
1503
}
 
1504
 
 
1505
/* Lower privileges permanently */
 
1506
__attribute__((warn_unused_result))
 
1507
error_t lower_privileges_permanently(void){
 
1508
  error_t old_errno = errno;
 
1509
  error_t ret_errno = 0;
 
1510
  if(setuid(uid) == -1){
 
1511
    ret_errno = errno;
 
1512
  }
 
1513
  errno = old_errno;
 
1514
  return ret_errno;
 
1515
}
 
1516
 
 
1517
__attribute__((nonnull))
 
1518
void run_network_hooks(const char *mode, const char *interface,
 
1519
                       const float delay){
 
1520
  struct dirent **direntries = NULL;
 
1521
  if(hookdir_fd == -1){
 
1522
    hookdir_fd = open(hookdir, O_RDONLY);
 
1523
    if(hookdir_fd == -1){
 
1524
      if(errno == ENOENT){
 
1525
        if(debug){
 
1526
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
 
1527
                       " found\n", hookdir);
 
1528
        }
 
1529
      } else {
 
1530
        perror_plus("open");
 
1531
      }
 
1532
      return;
 
1533
    }
 
1534
  }
 
1535
#ifdef __GLIBC__
 
1536
#if __GLIBC_PREREQ(2, 15)
 
1537
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
 
1538
                           runnable_hook, alphasort);
 
1539
#else  /* not __GLIBC_PREREQ(2, 15) */
 
1540
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1541
                         alphasort);
 
1542
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
1543
#else   /* not __GLIBC__ */
 
1544
  int numhooks = scandir(hookdir, &direntries, runnable_hook,
 
1545
                         alphasort);
 
1546
#endif  /* not __GLIBC__ */
 
1547
  if(numhooks == -1){
 
1548
    perror_plus("scandir");
 
1549
    return;
 
1550
  }
 
1551
  struct dirent *direntry;
 
1552
  int ret;
 
1553
  int devnull = open("/dev/null", O_RDONLY);
 
1554
  for(int i = 0; i < numhooks; i++){
 
1555
    direntry = direntries[i];
 
1556
    if(debug){
 
1557
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
 
1558
                   direntry->d_name);
 
1559
    }
 
1560
    pid_t hook_pid = fork();
 
1561
    if(hook_pid == 0){
 
1562
      /* Child */
 
1563
      /* Raise privileges */
 
1564
      errno = raise_privileges_permanently();
 
1565
      if(errno != 0){
 
1566
        perror_plus("Failed to raise privileges");
 
1567
        _exit(EX_NOPERM);
 
1568
      }
 
1569
      /* Set group */
 
1570
      errno = 0;
 
1571
      ret = setgid(0);
 
1572
      if(ret == -1){
 
1573
        perror_plus("setgid");
 
1574
        _exit(EX_NOPERM);
 
1575
      }
 
1576
      /* Reset supplementary groups */
 
1577
      errno = 0;
 
1578
      ret = setgroups(0, NULL);
 
1579
      if(ret == -1){
 
1580
        perror_plus("setgroups");
 
1581
        _exit(EX_NOPERM);
 
1582
      }
 
1583
      ret = dup2(devnull, STDIN_FILENO);
 
1584
      if(ret == -1){
 
1585
        perror_plus("dup2(devnull, STDIN_FILENO)");
 
1586
        _exit(EX_OSERR);
 
1587
      }
 
1588
      ret = close(devnull);
 
1589
      if(ret == -1){
 
1590
        perror_plus("close");
 
1591
        _exit(EX_OSERR);
 
1592
      }
 
1593
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
 
1594
      if(ret == -1){
 
1595
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
 
1596
        _exit(EX_OSERR);
 
1597
      }
 
1598
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
 
1599
      if(ret == -1){
 
1600
        perror_plus("setenv");
 
1601
        _exit(EX_OSERR);
 
1602
      }
 
1603
      ret = setenv("DEVICE", interface, 1);
 
1604
      if(ret == -1){
 
1605
        perror_plus("setenv");
 
1606
        _exit(EX_OSERR);
 
1607
      }
 
1608
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
 
1609
      if(ret == -1){
 
1610
        perror_plus("setenv");
 
1611
        _exit(EX_OSERR);
 
1612
      }
 
1613
      ret = setenv("MODE", mode, 1);
 
1614
      if(ret == -1){
 
1615
        perror_plus("setenv");
 
1616
        _exit(EX_OSERR);
 
1617
      }
 
1618
      char *delaystring;
 
1619
      ret = asprintf(&delaystring, "%f", (double)delay);
 
1620
      if(ret == -1){
 
1621
        perror_plus("asprintf");
 
1622
        _exit(EX_OSERR);
 
1623
      }
 
1624
      ret = setenv("DELAY", delaystring, 1);
 
1625
      if(ret == -1){
 
1626
        free(delaystring);
 
1627
        perror_plus("setenv");
 
1628
        _exit(EX_OSERR);
 
1629
      }
 
1630
      free(delaystring);
 
1631
      if(connect_to != NULL){
 
1632
        ret = setenv("CONNECT", connect_to, 1);
 
1633
        if(ret == -1){
 
1634
          perror_plus("setenv");
 
1635
          _exit(EX_OSERR);
 
1636
        }
 
1637
      }
 
1638
      int hook_fd = openat(hookdir_fd, direntry->d_name, O_RDONLY);
 
1639
      if(hook_fd == -1){
 
1640
        perror_plus("openat");
 
1641
        _exit(EXIT_FAILURE);
 
1642
      }
 
1643
      if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1644
        perror_plus("close");
 
1645
        _exit(EXIT_FAILURE);
 
1646
      }
 
1647
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
 
1648
                 environ) == -1){
 
1649
        perror_plus("fexecve");
 
1650
        _exit(EXIT_FAILURE);
 
1651
      }
 
1652
    } else {
 
1653
      int status;
 
1654
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
 
1655
        perror_plus("waitpid");
 
1656
        free(direntry);
 
1657
        continue;
 
1658
      }
 
1659
      if(WIFEXITED(status)){
 
1660
        if(WEXITSTATUS(status) != 0){
 
1661
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
 
1662
                       " with status %d\n", direntry->d_name,
 
1663
                       WEXITSTATUS(status));
 
1664
          free(direntry);
 
1665
          continue;
 
1666
        }
 
1667
      } else if(WIFSIGNALED(status)){
 
1668
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
 
1669
                     " signal %d\n", direntry->d_name,
 
1670
                     WTERMSIG(status));
 
1671
        free(direntry);
 
1672
        continue;
 
1673
      } else {
 
1674
        fprintf_plus(stderr, "Warning: network hook \"%s\""
 
1675
                     " crashed\n", direntry->d_name);
 
1676
        free(direntry);
 
1677
        continue;
 
1678
      }
 
1679
    }
 
1680
    if(debug){
 
1681
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
 
1682
                   direntry->d_name);
 
1683
    }
 
1684
    free(direntry);
 
1685
  }
 
1686
  free(direntries);
 
1687
  if((int)TEMP_FAILURE_RETRY(close(hookdir_fd)) == -1){
 
1688
    perror_plus("close");
 
1689
  } else {
 
1690
    hookdir_fd = -1;
 
1691
  }
 
1692
  close(devnull);
 
1693
}
 
1694
 
 
1695
__attribute__((nonnull, warn_unused_result))
 
1696
error_t bring_up_interface(const char *const interface,
 
1697
                           const float delay){
 
1698
  error_t old_errno = errno;
 
1699
  int ret;
 
1700
  struct ifreq network;
 
1701
  unsigned int if_index = if_nametoindex(interface);
 
1702
  if(if_index == 0){
 
1703
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1704
    errno = old_errno;
 
1705
    return ENXIO;
 
1706
  }
 
1707
  
 
1708
  if(quit_now){
 
1709
    errno = old_errno;
 
1710
    return EINTR;
 
1711
  }
 
1712
  
 
1713
  if(not interface_is_up(interface)){
 
1714
    error_t ret_errno = 0, ioctl_errno = 0;
 
1715
    if(not get_flags(interface, &network)){
 
1716
      ret_errno = errno;
 
1717
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1718
                   "\"%s\"\n", interface);
 
1719
      errno = old_errno;
 
1720
      return ret_errno;
 
1721
    }
 
1722
    network.ifr_flags |= IFF_UP; /* set flag */
 
1723
    
 
1724
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1725
    if(sd == -1){
 
1726
      ret_errno = errno;
 
1727
      perror_plus("socket");
 
1728
      errno = old_errno;
 
1729
      return ret_errno;
 
1730
    }
 
1731
    
 
1732
    if(quit_now){
 
1733
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1734
      if(ret == -1){
 
1735
        perror_plus("close");
 
1736
      }
 
1737
      errno = old_errno;
 
1738
      return EINTR;
 
1739
    }
 
1740
    
 
1741
    if(debug){
 
1742
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
 
1743
                   interface);
 
1744
    }
 
1745
    
 
1746
    /* Raise privileges */
 
1747
    ret_errno = raise_privileges();
 
1748
    if(ret_errno != 0){
 
1749
      errno = ret_errno;
 
1750
      perror_plus("Failed to raise privileges");
 
1751
    }
 
1752
    
 
1753
#ifdef __linux__
 
1754
    int ret_linux;
 
1755
    bool restore_loglevel = false;
 
1756
    if(ret_errno == 0){
 
1757
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1758
         messages about the network interface to mess up the prompt */
 
1759
      ret_linux = klogctl(8, NULL, 5);
 
1760
      if(ret_linux == -1){
 
1761
        perror_plus("klogctl");
 
1762
      } else {
 
1763
        restore_loglevel = true;
 
1764
      }
 
1765
    }
 
1766
#endif  /* __linux__ */
 
1767
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1768
    ioctl_errno = errno;
 
1769
#ifdef __linux__
 
1770
    if(restore_loglevel){
 
1771
      ret_linux = klogctl(7, NULL, 0);
 
1772
      if(ret_linux == -1){
 
1773
        perror_plus("klogctl");
 
1774
      }
 
1775
    }
 
1776
#endif  /* __linux__ */
 
1777
    
 
1778
    /* If raise_privileges() succeeded above */
 
1779
    if(ret_errno == 0){
 
1780
      /* Lower privileges */
 
1781
      ret_errno = lower_privileges();
 
1782
      if(ret_errno != 0){
 
1783
        errno = ret_errno;
 
1784
        perror_plus("Failed to lower privileges");
 
1785
      }
 
1786
    }
 
1787
    
 
1788
    /* Close the socket */
 
1789
    ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1790
    if(ret == -1){
 
1791
      perror_plus("close");
 
1792
    }
 
1793
    
 
1794
    if(ret_setflags == -1){
 
1795
      errno = ioctl_errno;
 
1796
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1797
      errno = old_errno;
 
1798
      return ioctl_errno;
 
1799
    }
 
1800
  } else if(debug){
 
1801
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
 
1802
                 interface);
 
1803
  }
 
1804
  
 
1805
  /* Sleep checking until interface is running.
 
1806
     Check every 0.25s, up to total time of delay */
 
1807
  for(int i=0; i < delay * 4; i++){
 
1808
    if(interface_is_running(interface)){
 
1809
      break;
 
1810
    }
 
1811
    struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1812
    ret = nanosleep(&sleeptime, NULL);
 
1813
    if(ret == -1 and errno != EINTR){
 
1814
      perror_plus("nanosleep");
 
1815
    }
 
1816
  }
 
1817
  
 
1818
  errno = old_errno;
 
1819
  return 0;
 
1820
}
 
1821
 
 
1822
__attribute__((nonnull, warn_unused_result))
 
1823
error_t take_down_interface(const char *const interface){
 
1824
  error_t old_errno = errno;
 
1825
  struct ifreq network;
 
1826
  unsigned int if_index = if_nametoindex(interface);
 
1827
  if(if_index == 0){
 
1828
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
 
1829
    errno = old_errno;
 
1830
    return ENXIO;
 
1831
  }
 
1832
  if(interface_is_up(interface)){
 
1833
    error_t ret_errno = 0, ioctl_errno = 0;
 
1834
    if(not get_flags(interface, &network) and debug){
 
1835
      ret_errno = errno;
 
1836
      fprintf_plus(stderr, "Failed to get flags for interface "
 
1837
                   "\"%s\"\n", interface);
 
1838
      errno = old_errno;
 
1839
      return ret_errno;
 
1840
    }
 
1841
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1842
    
 
1843
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1844
    if(sd == -1){
 
1845
      ret_errno = errno;
 
1846
      perror_plus("socket");
 
1847
      errno = old_errno;
 
1848
      return ret_errno;
 
1849
    }
 
1850
    
 
1851
    if(debug){
 
1852
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
 
1853
                   interface);
 
1854
    }
 
1855
    
 
1856
    /* Raise privileges */
 
1857
    ret_errno = raise_privileges();
 
1858
    if(ret_errno != 0){
 
1859
      errno = ret_errno;
 
1860
      perror_plus("Failed to raise privileges");
 
1861
    }
 
1862
    
 
1863
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
 
1864
    ioctl_errno = errno;
 
1865
    
 
1866
    /* If raise_privileges() succeeded above */
 
1867
    if(ret_errno == 0){
 
1868
      /* Lower privileges */
 
1869
      ret_errno = lower_privileges();
 
1870
      if(ret_errno != 0){
 
1871
        errno = ret_errno;
 
1872
        perror_plus("Failed to lower privileges");
 
1873
      }
 
1874
    }
 
1875
    
 
1876
    /* Close the socket */
 
1877
    int ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1878
    if(ret == -1){
 
1879
      perror_plus("close");
 
1880
    }
 
1881
    
 
1882
    if(ret_setflags == -1){
 
1883
      errno = ioctl_errno;
 
1884
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1885
      errno = old_errno;
 
1886
      return ioctl_errno;
 
1887
    }
 
1888
  } else if(debug){
 
1889
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
 
1890
                 interface);
 
1891
  }
 
1892
  
 
1893
  errno = old_errno;
 
1894
  return 0;
 
1895
}
 
1896
 
1343
1897
int main(int argc, char *argv[]){
 
1898
  mandos_context mc = { .server = NULL, .dh_bits = 1024,
 
1899
                        .priority = "SECURE256:!CTYPE-X.509:"
 
1900
                        "+CTYPE-OPENPGP", .current_server = NULL,
 
1901
                        .interfaces = NULL, .interfaces_size = 0 };
1344
1902
  AvahiSServiceBrowser *sb = NULL;
1345
 
  int error;
 
1903
  error_t ret_errno;
1346
1904
  int ret;
1347
1905
  intmax_t tmpmax;
1348
1906
  char *tmp;
1349
1907
  int exitcode = EXIT_SUCCESS;
1350
 
  const char *interface = "";
1351
 
  struct ifreq network;
1352
 
  int sd = -1;
1353
 
  bool take_down_interface = false;
1354
 
  uid_t uid;
1355
 
  gid_t gid;
1356
 
  char tempdir[] = "/tmp/mandosXXXXXX";
1357
 
  bool tempdir_created = false;
 
1908
  char *interfaces_to_take_down = NULL;
 
1909
  size_t interfaces_to_take_down_size = 0;
 
1910
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
 
1911
  char old_tempdir[] = "/tmp/mandosXXXXXX";
 
1912
  char *tempdir = NULL;
1358
1913
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1359
1914
  const char *seckey = PATHDIR "/" SECKEY;
1360
1915
  const char *pubkey = PATHDIR "/" PUBKEY;
 
1916
  char *interfaces_hooks = NULL;
1361
1917
  
1362
1918
  bool gnutls_initialized = false;
1363
1919
  bool gpgme_initialized = false;
1425
1981
        .group = 2 },
1426
1982
      { .name = "retry", .key = 132,
1427
1983
        .arg = "SECONDS",
1428
 
        .doc = "Retry interval used when denied by the mandos server",
 
1984
        .doc = "Retry interval used when denied by the Mandos server",
 
1985
        .group = 2 },
 
1986
      { .name = "network-hook-dir", .key = 133,
 
1987
        .arg = "DIR",
 
1988
        .doc = "Directory where network hooks are located",
1429
1989
        .group = 2 },
1430
1990
      /*
1431
1991
       * These reproduce what we would get without ARGP_NO_HELP
1450
2010
        connect_to = arg;
1451
2011
        break;
1452
2012
      case 'i':                 /* --interface */
1453
 
        interface = arg;
 
2013
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
 
2014
                                 arg, (int)',');
 
2015
        if(ret_errno != 0){
 
2016
          argp_error(state, "%s", strerror(ret_errno));
 
2017
        }
1454
2018
        break;
1455
2019
      case 's':                 /* --seckey */
1456
2020
        seckey = arg;
1485
2049
          argp_error(state, "Bad retry interval");
1486
2050
        }
1487
2051
        break;
 
2052
      case 133:                 /* --network-hook-dir */
 
2053
        hookdir = arg;
 
2054
        break;
1488
2055
        /*
1489
2056
         * These reproduce what we would get without ARGP_NO_HELP
1490
2057
         */
1496
2063
        argp_state_help(state, state->out_stream,
1497
2064
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1498
2065
      case 'V':                 /* --version */
1499
 
        fprintf(state->out_stream, "%s\n", argp_program_version);
 
2066
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
1500
2067
        exit(argp_err_exit_status);
1501
2068
        break;
1502
2069
      default:
1529
2096
  {
1530
2097
    /* Work around Debian bug #633582:
1531
2098
       <http://bugs.debian.org/633582> */
1532
 
    struct stat st;
1533
 
    
1534
 
    /* Re-raise priviliges */
1535
 
    errno = 0;
1536
 
    ret = seteuid(0);
1537
 
    if(ret == -1){
1538
 
      perror_plus("seteuid");
1539
 
    }
1540
 
    
1541
 
    if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
1542
 
      int seckey_fd = open(seckey, O_RDONLY);
1543
 
      if(seckey_fd == -1){
1544
 
        perror_plus("open");
1545
 
      } else {
1546
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
1547
 
        if(ret == -1){
1548
 
          perror_plus("fstat");
1549
 
        } else {
1550
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1551
 
            ret = fchown(seckey_fd, uid, gid);
1552
 
            if(ret == -1){
1553
 
              perror_plus("fchown");
1554
 
            }
1555
 
          }
1556
 
        }
1557
 
        TEMP_FAILURE_RETRY(close(seckey_fd));
1558
 
      }
1559
 
    }
1560
 
    
1561
 
    if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
1562
 
      int pubkey_fd = open(pubkey, O_RDONLY);
1563
 
      if(pubkey_fd == -1){
1564
 
        perror_plus("open");
1565
 
      } else {
1566
 
        ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
1567
 
        if(ret == -1){
1568
 
          perror_plus("fstat");
1569
 
        } else {
1570
 
          if(S_ISREG(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){
1571
 
            ret = fchown(pubkey_fd, uid, gid);
1572
 
            if(ret == -1){
1573
 
              perror_plus("fchown");
1574
 
            }
1575
 
          }
1576
 
        }
1577
 
        TEMP_FAILURE_RETRY(close(pubkey_fd));
1578
 
      }
1579
 
    }
1580
 
    
1581
 
    /* Lower privileges */
1582
 
    errno = 0;
1583
 
    ret = seteuid(uid);
1584
 
    if(ret == -1){
1585
 
      perror_plus("seteuid");
1586
 
    }
1587
 
  }
1588
 
  
1589
 
  /* Find network hooks and run them */
1590
 
  {
1591
 
    struct dirent **direntries;
1592
 
    struct dirent *direntry;
1593
 
    int numhooks = scandir(HOOKDIR, &direntries, runnable_hook,
1594
 
                           alphasort);
1595
 
    int devnull = open("/dev/null", O_RDONLY);
1596
 
    for(int i = 0; i < numhooks; i++){
1597
 
      direntry = direntries[0];
1598
 
      char *fullname = NULL;
1599
 
      ret = asprintf(&fullname, "%s/%s", tempdir,
1600
 
                     direntry->d_name);
1601
 
      if(ret < 0){
1602
 
        perror_plus("asprintf");
1603
 
        continue;
1604
 
      }
1605
 
      pid_t hook_pid = fork();
1606
 
      if(hook_pid == 0){
1607
 
        /* Child */
1608
 
        dup2(devnull, STDIN_FILENO);
1609
 
        close(devnull);
1610
 
        dup2(STDERR_FILENO, STDOUT_FILENO);
1611
 
        setenv("DEVICE", interface, 1);
1612
 
        setenv("VERBOSE", debug ? "1" : "0", 1);
1613
 
        setenv("MODE", "start", 1);
1614
 
        /* setenv( XXX more here */
1615
 
        ret = execl(fullname, direntry->d_name, "start", NULL);
1616
 
        perror_plus("execl");
1617
 
      }
1618
 
      free(fullname);
1619
 
      if(quit_now){
 
2099
    
 
2100
    /* Re-raise privileges */
 
2101
    ret_errno = raise_privileges();
 
2102
    if(ret_errno != 0){
 
2103
      errno = ret_errno;
 
2104
      perror_plus("Failed to raise privileges");
 
2105
    } else {
 
2106
      struct stat st;
 
2107
      
 
2108
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
 
2109
        int seckey_fd = open(seckey, O_RDONLY);
 
2110
        if(seckey_fd == -1){
 
2111
          perror_plus("open");
 
2112
        } else {
 
2113
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
 
2114
          if(ret == -1){
 
2115
            perror_plus("fstat");
 
2116
          } else {
 
2117
            if(S_ISREG(st.st_mode)
 
2118
               and st.st_uid == 0 and st.st_gid == 0){
 
2119
              ret = fchown(seckey_fd, uid, gid);
 
2120
              if(ret == -1){
 
2121
                perror_plus("fchown");
 
2122
              }
 
2123
            }
 
2124
          }
 
2125
          TEMP_FAILURE_RETRY(close(seckey_fd));
 
2126
        }
 
2127
      }
 
2128
    
 
2129
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
 
2130
        int pubkey_fd = open(pubkey, O_RDONLY);
 
2131
        if(pubkey_fd == -1){
 
2132
          perror_plus("open");
 
2133
        } else {
 
2134
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
 
2135
          if(ret == -1){
 
2136
            perror_plus("fstat");
 
2137
          } else {
 
2138
            if(S_ISREG(st.st_mode)
 
2139
               and st.st_uid == 0 and st.st_gid == 0){
 
2140
              ret = fchown(pubkey_fd, uid, gid);
 
2141
              if(ret == -1){
 
2142
                perror_plus("fchown");
 
2143
              }
 
2144
            }
 
2145
          }
 
2146
          TEMP_FAILURE_RETRY(close(pubkey_fd));
 
2147
        }
 
2148
      }
 
2149
    
 
2150
      /* Lower privileges */
 
2151
      ret_errno = lower_privileges();
 
2152
      if(ret_errno != 0){
 
2153
        errno = ret_errno;
 
2154
        perror_plus("Failed to lower privileges");
 
2155
      }
 
2156
    }
 
2157
  }
 
2158
  
 
2159
  /* Remove invalid interface names (except "none") */
 
2160
  {
 
2161
    char *interface = NULL;
 
2162
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2163
                                 interface))){
 
2164
      if(strcmp(interface, "none") != 0
 
2165
         and if_nametoindex(interface) == 0){
 
2166
        if(interface[0] != '\0'){
 
2167
          fprintf_plus(stderr, "Not using nonexisting interface"
 
2168
                       " \"%s\"\n", interface);
 
2169
        }
 
2170
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
 
2171
        interface = NULL;
 
2172
      }
 
2173
    }
 
2174
  }
 
2175
  
 
2176
  /* Run network hooks */
 
2177
  {
 
2178
    if(mc.interfaces != NULL){
 
2179
      interfaces_hooks = malloc(mc.interfaces_size);
 
2180
      if(interfaces_hooks == NULL){
 
2181
        perror_plus("malloc");
1620
2182
        goto end;
1621
2183
      }
 
2184
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
 
2185
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
1622
2186
    }
1623
 
    close(devnull);
 
2187
    run_network_hooks("start", interfaces_hooks != NULL ?
 
2188
                      interfaces_hooks : "", delay);
1624
2189
  }
1625
2190
  
1626
2191
  if(not debug){
1627
2192
    avahi_set_log_function(empty_log);
1628
2193
  }
1629
2194
  
1630
 
  if(interface[0] == '\0'){
1631
 
    struct dirent **direntries;
1632
 
    /* First look for interfaces that are up */
1633
 
    ret = scandir(sys_class_net, &direntries, up_interface,
1634
 
                  alphasort);
1635
 
    if(ret == 0){
1636
 
      /* No up interfaces, look for any good interfaces */
1637
 
      free(direntries);
1638
 
      ret = scandir(sys_class_net, &direntries, good_interface,
1639
 
                    alphasort);
1640
 
    }
1641
 
    if(ret >= 1){
1642
 
      /* Pick the first interface returned */
1643
 
      interface = strdup(direntries[0]->d_name);
1644
 
      if(debug){
1645
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
1646
 
      }
1647
 
      if(interface == NULL){
1648
 
        perror_plus("malloc");
1649
 
        free(direntries);
1650
 
        exitcode = EXIT_FAILURE;
1651
 
        goto end;
1652
 
      }
1653
 
      free(direntries);
1654
 
    } else {
1655
 
      free(direntries);
1656
 
      fprintf(stderr, "Could not find a network interface\n");
1657
 
      exitcode = EXIT_FAILURE;
1658
 
      goto end;
1659
 
    }
1660
 
  }
1661
 
  
1662
2195
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1663
2196
     from the signal handler */
1664
2197
  /* Initialize the pseudo-RNG for Avahi */
1665
2198
  srand((unsigned int) time(NULL));
1666
 
  mc.simple_poll = avahi_simple_poll_new();
1667
 
  if(mc.simple_poll == NULL){
1668
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
2199
  simple_poll = avahi_simple_poll_new();
 
2200
  if(simple_poll == NULL){
 
2201
    fprintf_plus(stderr,
 
2202
                 "Avahi: Failed to create simple poll object.\n");
1669
2203
    exitcode = EX_UNAVAILABLE;
1670
2204
    goto end;
1671
2205
  }
1733
2267
    }
1734
2268
  }
1735
2269
  
1736
 
  /* If the interface is down, bring it up */
1737
 
  if(strcmp(interface, "none") != 0){
1738
 
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1739
 
    if(if_index == 0){
1740
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
1741
 
      exitcode = EX_UNAVAILABLE;
1742
 
      goto end;
1743
 
    }
1744
 
    
1745
 
    if(quit_now){
1746
 
      goto end;
1747
 
    }
1748
 
    
1749
 
    /* Re-raise priviliges */
1750
 
    errno = 0;
1751
 
    ret = seteuid(0);
1752
 
    if(ret == -1){
1753
 
      perror_plus("seteuid");
1754
 
    }
1755
 
    
1756
 
#ifdef __linux__
1757
 
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1758
 
       messages about the network interface to mess up the prompt */
1759
 
    ret = klogctl(8, NULL, 5);
1760
 
    bool restore_loglevel = true;
1761
 
    if(ret == -1){
1762
 
      restore_loglevel = false;
1763
 
      perror_plus("klogctl");
1764
 
    }
1765
 
#endif  /* __linux__ */
1766
 
    
1767
 
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1768
 
    if(sd < 0){
1769
 
      perror_plus("socket");
1770
 
      exitcode = EX_OSERR;
1771
 
#ifdef __linux__
1772
 
      if(restore_loglevel){
1773
 
        ret = klogctl(7, NULL, 0);
1774
 
        if(ret == -1){
1775
 
          perror_plus("klogctl");
1776
 
        }
1777
 
      }
1778
 
#endif  /* __linux__ */
1779
 
      /* Lower privileges */
1780
 
      errno = 0;
1781
 
      ret = seteuid(uid);
1782
 
      if(ret == -1){
1783
 
        perror_plus("seteuid");
1784
 
      }
1785
 
      goto end;
1786
 
    }
1787
 
    strcpy(network.ifr_name, interface);
1788
 
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1789
 
    if(ret == -1){
1790
 
      perror_plus("ioctl SIOCGIFFLAGS");
1791
 
#ifdef __linux__
1792
 
      if(restore_loglevel){
1793
 
        ret = klogctl(7, NULL, 0);
1794
 
        if(ret == -1){
1795
 
          perror_plus("klogctl");
1796
 
        }
1797
 
      }
1798
 
#endif  /* __linux__ */
1799
 
      exitcode = EX_OSERR;
1800
 
      /* Lower privileges */
1801
 
      errno = 0;
1802
 
      ret = seteuid(uid);
1803
 
      if(ret == -1){
1804
 
        perror_plus("seteuid");
1805
 
      }
1806
 
      goto end;
1807
 
    }
1808
 
    if((network.ifr_flags & IFF_UP) == 0){
1809
 
      network.ifr_flags |= IFF_UP;
1810
 
      take_down_interface = true;
1811
 
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1812
 
      if(ret == -1){
1813
 
        take_down_interface = false;
1814
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1815
 
        exitcode = EX_OSERR;
1816
 
#ifdef __linux__
1817
 
        if(restore_loglevel){
1818
 
          ret = klogctl(7, NULL, 0);
1819
 
          if(ret == -1){
1820
 
            perror_plus("klogctl");
 
2270
  /* If no interfaces were specified, make a list */
 
2271
  if(mc.interfaces == NULL){
 
2272
    struct dirent **direntries = NULL;
 
2273
    /* Look for any good interfaces */
 
2274
    ret = scandir(sys_class_net, &direntries, good_interface,
 
2275
                  alphasort);
 
2276
    if(ret >= 1){
 
2277
      /* Add all found interfaces to interfaces list */
 
2278
      for(int i = 0; i < ret; ++i){
 
2279
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
 
2280
                             direntries[i]->d_name);
 
2281
        if(ret_errno != 0){
 
2282
          errno = ret_errno;
 
2283
          perror_plus("argz_add");
 
2284
          free(direntries[i]);
 
2285
          continue;
 
2286
        }
 
2287
        if(debug){
 
2288
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
 
2289
                       direntries[i]->d_name);
 
2290
        }
 
2291
        free(direntries[i]);
 
2292
      }
 
2293
      free(direntries);
 
2294
    } else {
 
2295
      if(ret == 0){
 
2296
        free(direntries);
 
2297
      }
 
2298
      fprintf_plus(stderr, "Could not find a network interface\n");
 
2299
      exitcode = EXIT_FAILURE;
 
2300
      goto end;
 
2301
    }
 
2302
  }
 
2303
  
 
2304
  /* Bring up interfaces which are down, and remove any "none"s */
 
2305
  {
 
2306
    char *interface = NULL;
 
2307
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
 
2308
                                 interface))){
 
2309
      /* If interface name is "none", stop bringing up interfaces.
 
2310
         Also remove all instances of "none" from the list */
 
2311
      if(strcmp(interface, "none") == 0){
 
2312
        argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2313
                    interface);
 
2314
        interface = NULL;
 
2315
        while((interface = argz_next(mc.interfaces,
 
2316
                                     mc.interfaces_size, interface))){
 
2317
          if(strcmp(interface, "none") == 0){
 
2318
            argz_delete(&mc.interfaces, &mc.interfaces_size,
 
2319
                        interface);
 
2320
            interface = NULL;
1821
2321
          }
1822
2322
        }
1823
 
#endif  /* __linux__ */
1824
 
        /* Lower privileges */
1825
 
        errno = 0;
1826
 
        ret = seteuid(uid);
1827
 
        if(ret == -1){
1828
 
          perror_plus("seteuid");
1829
 
        }
1830
 
        goto end;
1831
 
      }
1832
 
    }
1833
 
    /* Sleep checking until interface is running.
1834
 
       Check every 0.25s, up to total time of delay */
1835
 
    for(int i=0; i < delay * 4; i++){
1836
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1837
 
      if(ret == -1){
1838
 
        perror_plus("ioctl SIOCGIFFLAGS");
1839
 
      } else if(network.ifr_flags & IFF_RUNNING){
1840
2323
        break;
1841
2324
      }
1842
 
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1843
 
      ret = nanosleep(&sleeptime, NULL);
1844
 
      if(ret == -1 and errno != EINTR){
1845
 
        perror_plus("nanosleep");
1846
 
      }
1847
 
    }
1848
 
    if(not take_down_interface){
1849
 
      /* We won't need the socket anymore */
1850
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1851
 
      if(ret == -1){
1852
 
        perror_plus("close");
1853
 
      }
1854
 
    }
1855
 
#ifdef __linux__
1856
 
    if(restore_loglevel){
1857
 
      /* Restores kernel loglevel to default */
1858
 
      ret = klogctl(7, NULL, 0);
1859
 
      if(ret == -1){
1860
 
        perror_plus("klogctl");
1861
 
      }
1862
 
    }
1863
 
#endif  /* __linux__ */
1864
 
    /* Lower privileges */
1865
 
    errno = 0;
1866
 
    if(take_down_interface){
1867
 
      /* Lower privileges */
1868
 
      ret = seteuid(uid);
1869
 
      if(ret == -1){
1870
 
        perror_plus("seteuid");
1871
 
      }
1872
 
    } else {
1873
 
      /* Lower privileges permanently */
1874
 
      ret = setuid(uid);
1875
 
      if(ret == -1){
1876
 
        perror_plus("setuid");
1877
 
      }
1878
 
    }
 
2325
      bool interface_was_up = interface_is_up(interface);
 
2326
      errno = bring_up_interface(interface, delay);
 
2327
      if(not interface_was_up){
 
2328
        if(errno != 0){
 
2329
          perror_plus("Failed to bring up interface");
 
2330
        } else {
 
2331
          errno = argz_add(&interfaces_to_take_down,
 
2332
                           &interfaces_to_take_down_size,
 
2333
                           interface);
 
2334
          if(errno != 0){
 
2335
            perror_plus("argz_add");
 
2336
          }
 
2337
        }
 
2338
      }
 
2339
    }
 
2340
    if(debug and (interfaces_to_take_down == NULL)){
 
2341
      fprintf_plus(stderr, "No interfaces were brought up\n");
 
2342
    }
 
2343
  }
 
2344
  
 
2345
  /* If we only got one interface, explicitly use only that one */
 
2346
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
 
2347
    if(debug){
 
2348
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
 
2349
                   mc.interfaces);
 
2350
    }
 
2351
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
1879
2352
  }
1880
2353
  
1881
2354
  if(quit_now){
1882
2355
    goto end;
1883
2356
  }
1884
2357
  
1885
 
  ret = init_gnutls_global(pubkey, seckey);
 
2358
  ret = init_gnutls_global(pubkey, seckey, &mc);
1886
2359
  if(ret == -1){
1887
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2360
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1888
2361
    exitcode = EX_UNAVAILABLE;
1889
2362
    goto end;
1890
2363
  } else {
1895
2368
    goto end;
1896
2369
  }
1897
2370
  
1898
 
  if(mkdtemp(tempdir) == NULL){
 
2371
  /* Try /run/tmp before /tmp */
 
2372
  tempdir = mkdtemp(run_tempdir);
 
2373
  if(tempdir == NULL and errno == ENOENT){
 
2374
      if(debug){
 
2375
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
 
2376
                     run_tempdir, old_tempdir);
 
2377
      }
 
2378
      tempdir = mkdtemp(old_tempdir);
 
2379
  }
 
2380
  if(tempdir == NULL){
1899
2381
    perror_plus("mkdtemp");
1900
2382
    goto end;
1901
2383
  }
1902
 
  tempdir_created = true;
1903
2384
  
1904
2385
  if(quit_now){
1905
2386
    goto end;
1906
2387
  }
1907
2388
  
1908
 
  if(not init_gpgme(pubkey, seckey, tempdir)){
1909
 
    fprintf(stderr, "init_gpgme failed\n");
 
2389
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
 
2390
    fprintf_plus(stderr, "init_gpgme failed\n");
1910
2391
    exitcode = EX_UNAVAILABLE;
1911
2392
    goto end;
1912
2393
  } else {
1921
2402
    /* Connect directly, do not use Zeroconf */
1922
2403
    /* (Mainly meant for debugging) */
1923
2404
    char *address = strrchr(connect_to, ':');
 
2405
    
1924
2406
    if(address == NULL){
1925
 
      fprintf(stderr, "No colon in address\n");
 
2407
      fprintf_plus(stderr, "No colon in address\n");
1926
2408
      exitcode = EX_USAGE;
1927
2409
      goto end;
1928
2410
    }
1931
2413
      goto end;
1932
2414
    }
1933
2415
    
1934
 
    uint16_t port;
 
2416
    in_port_t port;
1935
2417
    errno = 0;
1936
2418
    tmpmax = strtoimax(address+1, &tmp, 10);
1937
2419
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1938
 
       or tmpmax != (uint16_t)tmpmax){
1939
 
      fprintf(stderr, "Bad port number\n");
 
2420
       or tmpmax != (in_port_t)tmpmax){
 
2421
      fprintf_plus(stderr, "Bad port number\n");
1940
2422
      exitcode = EX_USAGE;
1941
2423
      goto end;
1942
2424
    }
1943
 
  
 
2425
    
1944
2426
    if(quit_now){
1945
2427
      goto end;
1946
2428
    }
1947
2429
    
1948
 
    port = (uint16_t)tmpmax;
 
2430
    port = (in_port_t)tmpmax;
1949
2431
    *address = '\0';
1950
2432
    /* Colon in address indicates IPv6 */
1951
2433
    int af;
1967
2449
    }
1968
2450
    
1969
2451
    while(not quit_now){
1970
 
      ret = start_mandos_communication(address, port, if_index, af);
 
2452
      ret = start_mandos_communication(address, port, if_index, af,
 
2453
                                       &mc);
1971
2454
      if(quit_now or ret == 0){
1972
2455
        break;
1973
2456
      }
1974
2457
      if(debug){
1975
 
        fprintf(stderr, "Retrying in %d seconds\n",
1976
 
                (int)retry_interval);
 
2458
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2459
                     (int)retry_interval);
1977
2460
      }
1978
 
      sleep((int)retry_interval);
 
2461
      sleep((unsigned int)retry_interval);
1979
2462
    }
1980
2463
    
1981
 
    if (not quit_now){
 
2464
    if(not quit_now){
1982
2465
      exitcode = EXIT_SUCCESS;
1983
2466
    }
1984
2467
    
1999
2482
    config.publish_domain = 0;
2000
2483
    
2001
2484
    /* Allocate a new server */
2002
 
    mc.server = avahi_server_new(avahi_simple_poll_get
2003
 
                                 (mc.simple_poll), &config, NULL,
2004
 
                                 NULL, &error);
 
2485
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
 
2486
                                 &config, NULL, NULL, &ret_errno);
2005
2487
    
2006
2488
    /* Free the Avahi configuration data */
2007
2489
    avahi_server_config_free(&config);
2009
2491
  
2010
2492
  /* Check if creating the Avahi server object succeeded */
2011
2493
  if(mc.server == NULL){
2012
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2013
 
            avahi_strerror(error));
 
2494
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2495
                 avahi_strerror(ret_errno));
2014
2496
    exitcode = EX_UNAVAILABLE;
2015
2497
    goto end;
2016
2498
  }
2022
2504
  /* Create the Avahi service browser */
2023
2505
  sb = avahi_s_service_browser_new(mc.server, if_index,
2024
2506
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2025
 
                                   NULL, 0, browse_callback, NULL);
 
2507
                                   NULL, 0, browse_callback,
 
2508
                                   (void *)&mc);
2026
2509
  if(sb == NULL){
2027
 
    fprintf(stderr, "Failed to create service browser: %s\n",
2028
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
2510
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
 
2511
                 avahi_strerror(avahi_server_errno(mc.server)));
2029
2512
    exitcode = EX_UNAVAILABLE;
2030
2513
    goto end;
2031
2514
  }
2037
2520
  /* Run the main loop */
2038
2521
  
2039
2522
  if(debug){
2040
 
    fprintf(stderr, "Starting Avahi loop search\n");
 
2523
    fprintf_plus(stderr, "Starting Avahi loop search\n");
2041
2524
  }
2042
 
 
2043
 
  ret = avahi_loop_with_timeout(mc.simple_poll,
2044
 
                                (int)(retry_interval * 1000));
 
2525
  
 
2526
  ret = avahi_loop_with_timeout(simple_poll,
 
2527
                                (int)(retry_interval * 1000), &mc);
2045
2528
  if(debug){
2046
 
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
2047
 
            (ret == 0) ? "successfully" : "with error");
 
2529
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
 
2530
                 (ret == 0) ? "successfully" : "with error");
2048
2531
  }
2049
2532
  
2050
2533
 end:
2051
2534
  
2052
2535
  if(debug){
2053
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2536
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
2054
2537
  }
2055
2538
  
2056
2539
  /* Cleanup things */
 
2540
  free(mc.interfaces);
 
2541
  
2057
2542
  if(sb != NULL)
2058
2543
    avahi_s_service_browser_free(sb);
2059
2544
  
2060
2545
  if(mc.server != NULL)
2061
2546
    avahi_server_free(mc.server);
2062
2547
  
2063
 
  if(mc.simple_poll != NULL)
2064
 
    avahi_simple_poll_free(mc.simple_poll);
 
2548
  if(simple_poll != NULL)
 
2549
    avahi_simple_poll_free(simple_poll);
2065
2550
  
2066
2551
  if(gnutls_initialized){
2067
2552
    gnutls_certificate_free_credentials(mc.cred);
2072
2557
  if(gpgme_initialized){
2073
2558
    gpgme_release(mc.ctx);
2074
2559
  }
2075
 
 
 
2560
  
2076
2561
  /* Cleans up the circular linked list of Mandos servers the client
2077
2562
     has seen */
2078
2563
  if(mc.current_server != NULL){
2079
2564
    mc.current_server->prev->next = NULL;
2080
2565
    while(mc.current_server != NULL){
2081
2566
      server *next = mc.current_server->next;
 
2567
#ifdef __GNUC__
 
2568
#pragma GCC diagnostic push
 
2569
#pragma GCC diagnostic ignored "-Wcast-qual"
 
2570
#endif
 
2571
      free((char *)(mc.current_server->ip));
 
2572
#ifdef __GNUC__
 
2573
#pragma GCC diagnostic pop
 
2574
#endif
2082
2575
      free(mc.current_server);
2083
2576
      mc.current_server = next;
2084
2577
    }
2085
2578
  }
2086
2579
  
2087
 
  /* XXX run network hooks "stop" here  */
2088
 
  
2089
 
  /* Take down the network interface */
2090
 
  if(take_down_interface){
2091
 
    /* Re-raise priviliges */
2092
 
    errno = 0;
2093
 
    ret = seteuid(0);
2094
 
    if(ret == -1){
2095
 
      perror_plus("seteuid");
 
2580
  /* Re-raise privileges */
 
2581
  {
 
2582
    ret_errno = raise_privileges();
 
2583
    if(ret_errno != 0){
 
2584
      errno = ret_errno;
 
2585
      perror_plus("Failed to raise privileges");
 
2586
    } else {
 
2587
      
 
2588
      /* Run network hooks */
 
2589
      run_network_hooks("stop", interfaces_hooks != NULL ?
 
2590
                        interfaces_hooks : "", delay);
 
2591
      
 
2592
      /* Take down the network interfaces which were brought up */
 
2593
      {
 
2594
        char *interface = NULL;
 
2595
        while((interface=argz_next(interfaces_to_take_down,
 
2596
                                   interfaces_to_take_down_size,
 
2597
                                   interface))){
 
2598
          ret_errno = take_down_interface(interface);
 
2599
          if(ret_errno != 0){
 
2600
            errno = ret_errno;
 
2601
            perror_plus("Failed to take down interface");
 
2602
          }
 
2603
        }
 
2604
        if(debug and (interfaces_to_take_down == NULL)){
 
2605
          fprintf_plus(stderr, "No interfaces needed to be taken"
 
2606
                       " down\n");
 
2607
        }
 
2608
      }
2096
2609
    }
2097
 
    if(geteuid() == 0){
2098
 
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2099
 
      if(ret == -1){
2100
 
        perror_plus("ioctl SIOCGIFFLAGS");
2101
 
      } else if(network.ifr_flags & IFF_UP) {
2102
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2103
 
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2104
 
        if(ret == -1){
2105
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2106
 
        }
2107
 
      }
2108
 
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2109
 
      if(ret == -1){
2110
 
        perror_plus("close");
2111
 
      }
2112
 
      /* Lower privileges permanently */
2113
 
      errno = 0;
2114
 
      ret = setuid(uid);
2115
 
      if(ret == -1){
2116
 
        perror_plus("setuid");
2117
 
      }
 
2610
    
 
2611
    ret_errno = lower_privileges_permanently();
 
2612
    if(ret_errno != 0){
 
2613
      errno = ret_errno;
 
2614
      perror_plus("Failed to lower privileges permanently");
2118
2615
    }
2119
2616
  }
2120
2617
  
 
2618
  free(interfaces_to_take_down);
 
2619
  free(interfaces_hooks);
 
2620
  
2121
2621
  /* Removes the GPGME temp directory and all files inside */
2122
 
  if(tempdir_created){
 
2622
  if(tempdir != NULL){
2123
2623
    struct dirent **direntries = NULL;
2124
 
    struct dirent *direntry = NULL;
2125
 
    int numentries = scandir(tempdir, &direntries, notdotentries,
2126
 
                             alphasort);
2127
 
    if (numentries > 0){
2128
 
      for(int i = 0; i < numentries; i++){
2129
 
        direntry = direntries[i];
2130
 
        char *fullname = NULL;
2131
 
        ret = asprintf(&fullname, "%s/%s", tempdir,
2132
 
                       direntry->d_name);
2133
 
        if(ret < 0){
2134
 
          perror_plus("asprintf");
2135
 
          continue;
2136
 
        }
2137
 
        ret = remove(fullname);
2138
 
        if(ret == -1){
2139
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
2140
 
                  strerror(errno));
2141
 
        }
2142
 
        free(fullname);
 
2624
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY |
 
2625
                                                  O_NOFOLLOW));
 
2626
    if(tempdir_fd == -1){
 
2627
      perror_plus("open");
 
2628
    } else {
 
2629
#ifdef __GLIBC__
 
2630
#if __GLIBC_PREREQ(2, 15)
 
2631
      int numentries = scandirat(tempdir_fd, ".", &direntries,
 
2632
                                 notdotentries, alphasort);
 
2633
#else  /* not __GLIBC_PREREQ(2, 15) */
 
2634
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2635
                               alphasort);
 
2636
#endif  /* not __GLIBC_PREREQ(2, 15) */
 
2637
#else   /* not __GLIBC__ */
 
2638
      int numentries = scandir(tempdir, &direntries, notdotentries,
 
2639
                               alphasort);
 
2640
#endif  /* not __GLIBC__ */
 
2641
      if(numentries >= 0){
 
2642
        for(int i = 0; i < numentries; i++){
 
2643
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
 
2644
          if(ret == -1){
 
2645
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
 
2646
                         " \"%s\", 0): %s\n", tempdir,
 
2647
                         direntries[i]->d_name, strerror(errno));
 
2648
          }
 
2649
          free(direntries[i]);
 
2650
        }
 
2651
        
 
2652
        /* need to clean even if 0 because man page doesn't specify */
 
2653
        free(direntries);
 
2654
        if(numentries == -1){
 
2655
          perror_plus("scandir");
 
2656
        }
 
2657
        ret = rmdir(tempdir);
 
2658
        if(ret == -1 and errno != ENOENT){
 
2659
          perror_plus("rmdir");
 
2660
        }
2143
2661
      }
2144
 
    }
2145
 
 
2146
 
    /* need to clean even if 0 because man page doesn't specify */
2147
 
    free(direntries);
2148
 
    if (numentries == -1){
2149
 
      perror_plus("scandir");
2150
 
    }
2151
 
    ret = rmdir(tempdir);
2152
 
    if(ret == -1 and errno != ENOENT){
2153
 
      perror_plus("rmdir");
 
2662
      TEMP_FAILURE_RETRY(close(tempdir_fd));
2154
2663
    }
2155
2664
  }
2156
2665