/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-06-14 02:55:24 UTC
  • Revision ID: teddy@recompile.se-20140614025524-k03150tjp4t89w1d
plugin-runner: Restore resources correctly if fork() fails.

* plugin-runner.c (main): If fork() fails, close pipe FD's and restore
                          signal mask for SIGCHLD.

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