/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: Björn Påhlsson
  • Date: 2011-06-23 22:27:15 UTC
  • mto: This revision was merged to the branch mainline in revision 485.
  • Revision ID: belorn@fukt.bsnet.se-20110623222715-q5wro9ma9iyjl367
* Makefile (CFLAGS): Added "-lrt" to include real time library.
* plugins.d/mandos-client.c: use scandir(3) instead of readdir(3)
                             Prefix all debug output with "Mandos plugin " + program_invocation_short_name
                             Retry servers that failed to provide password.
                             New option --retry SECONDS that sets the interval between rechecking.
                             --retry also controls how often it retries a server when using --connect.
* plugins.d/splashy.c:  Prefix all debug output with "Mandos plugin " + program_invocation_short_name
* plugins.d/usplash.c: --||--
* plugins.d/askpass-fifo.c: --||--
* plugins.d/password-prompt.c: --||--
* plugins.d/plymouth.c: --||--
* mandos: Lower logger level from warning to info on failed client requests because client was disabled or unknown fingerprint.
* plugins.d/plymouth.c (get_pid): bug fix. Was not calling free on direntries. 

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-2016 Teddy Hogeborn
13
 
 * Copyright © 2008-2016 Björn Påhlsson
 
12
 * Copyright © 2008-2011 Teddy Hogeborn
 
13
 * Copyright © 2008-2011 Björn Påhlsson
14
14
 * 
15
15
 * This program is free software: you can redistribute it and/or
16
16
 * modify it under the terms of the GNU General Public License as
26
26
 * along with this program.  If not, see
27
27
 * <http://www.gnu.org/licenses/>.
28
28
 * 
29
 
 * Contact the authors at <mandos@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.se>.
30
30
 */
31
31
 
32
32
/* Needed by GPGME, specifically gpgme_data_seek() */
33
33
#ifndef _LARGEFILE_SOURCE
34
34
#define _LARGEFILE_SOURCE
35
 
#endif  /* not _LARGEFILE_SOURCE */
 
35
#endif
36
36
#ifndef _FILE_OFFSET_BITS
37
37
#define _FILE_OFFSET_BITS 64
38
 
#endif  /* not _FILE_OFFSET_BITS */
 
38
#endif
39
39
 
40
40
#define _GNU_SOURCE             /* TEMP_FAILURE_RETRY(), asprintf() */
41
41
 
42
42
#include <stdio.h>              /* fprintf(), stderr, fwrite(),
43
 
                                   stdout, ferror() */
44
 
#include <stdint.h>             /* uint16_t, uint32_t, intptr_t */
 
43
                                   stdout, ferror(), remove() */
 
44
#include <stdint.h>             /* uint16_t, uint32_t */
45
45
#include <stddef.h>             /* NULL, size_t, ssize_t */
46
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, srand(),
47
47
                                   strtof(), abort() */
48
48
#include <stdbool.h>            /* bool, false, true */
49
 
#include <string.h>             /* strcmp(), strlen(), strerror(),
50
 
                                   asprintf(), strncpy() */
 
49
#include <string.h>             /* memset(), strcmp(), strlen(),
 
50
                                   strerror(), asprintf(), strcpy() */
51
51
#include <sys/ioctl.h>          /* ioctl */
52
52
#include <sys/types.h>          /* socket(), inet_pton(), sockaddr,
53
53
                                   sockaddr_in6, PF_INET6,
54
54
                                   SOCK_STREAM, uid_t, gid_t, open(),
55
55
                                   opendir(), DIR */
56
 
#include <sys/stat.h>           /* open(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
57
57
#include <sys/socket.h>         /* socket(), struct sockaddr_in6,
58
 
                                   inet_pton(), connect(),
59
 
                                   getnameinfo() */
60
 
#include <fcntl.h>              /* open(), unlinkat() */
 
58
                                   inet_pton(), connect() */
 
59
#include <fcntl.h>              /* open() */
61
60
#include <dirent.h>             /* opendir(), struct dirent, readdir()
62
61
                                 */
63
62
#include <inttypes.h>           /* PRIu16, PRIdMAX, intmax_t,
64
63
                                   strtoimax() */
65
 
#include <errno.h>              /* perror(), errno,
66
 
                                   program_invocation_short_name */
 
64
#include <assert.h>             /* assert() */
 
65
#include <errno.h>              /* perror(), errno, program_invocation_short_name */
67
66
#include <time.h>               /* nanosleep(), time(), sleep() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
73
72
                                */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
 
                                   setgid(), pause(), _exit(),
77
 
                                   unlinkat() */
78
 
#include <arpa/inet.h>          /* inet_pton(), htons() */
 
75
                                   setgid(), pause() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
79
77
#include <iso646.h>             /* not, or, and */
80
78
#include <argp.h>               /* struct argp_option, error_t, struct
81
79
                                   argp_state, struct argp,
86
84
                                   raise() */
87
85
#include <sysexits.h>           /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE,
88
86
                                   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() */
98
87
 
99
88
#ifdef __linux__
100
89
#include <sys/klog.h>           /* klogctl() */
118
107
                                   init_gnutls_session(),
119
108
                                   GNUTLS_* */
120
109
#include <gnutls/openpgp.h>
121
 
                         /* gnutls_certificate_set_openpgp_key_file(),
122
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
110
                          /* gnutls_certificate_set_openpgp_key_file(),
 
111
                                   GNUTLS_OPENPGP_FMT_BASE64 */
123
112
 
124
113
/* GPGME */
125
114
#include <gpgme.h>              /* All GPGME types, constants and
133
122
#define PATHDIR "/conf/conf.d/mandos"
134
123
#define SECKEY "seckey.txt"
135
124
#define PUBKEY "pubkey.txt"
136
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
137
125
 
138
126
bool debug = false;
139
127
static const char mandos_protocol_version[] = "1";
140
128
const char *argp_program_version = "mandos-client " VERSION;
141
 
const char *argp_program_bug_address = "<mandos@recompile.se>";
 
129
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
142
130
static const char sys_class_net[] = "/sys/class/net";
143
131
char *connect_to = NULL;
144
 
const char *hookdir = HOOKDIR;
145
 
int hookdir_fd = -1;
146
 
uid_t uid = 65534;
147
 
gid_t gid = 65534;
148
132
 
149
 
/* Doubly linked list that need to be circularly linked when used */
 
133
/* Doubly linked list that need to be circular linked when ever used */
150
134
typedef struct server{
151
135
  const char *ip;
152
 
  in_port_t port;
 
136
  uint16_t port;
153
137
  AvahiIfIndex if_index;
154
138
  int af;
155
139
  struct timespec last_seen;
159
143
 
160
144
/* Used for passing in values through the Avahi callback functions */
161
145
typedef struct {
 
146
  AvahiSimplePoll *simple_poll;
162
147
  AvahiServer *server;
163
148
  gnutls_certificate_credentials_t cred;
164
149
  unsigned int dh_bits;
166
151
  const char *priority;
167
152
  gpgme_ctx_t ctx;
168
153
  server *current_server;
169
 
  char *interfaces;
170
 
  size_t interfaces_size;
171
154
} mandos_context;
172
155
 
173
 
/* global so signal handler can reach it*/
174
 
AvahiSimplePoll *simple_poll;
 
156
/* global context so signal handler can reach it*/
 
157
mandos_context mc = { .simple_poll = NULL, .server = NULL,
 
158
                      .dh_bits = 1024, .priority = "SECURE256"
 
159
                      ":!CTYPE-X.509:+CTYPE-OPENPGP", .current_server = NULL };
175
160
 
176
161
sig_atomic_t quit_now = 0;
177
162
int signal_received = 0;
178
163
 
179
164
/* Function to use when printing errors */
180
165
void perror_plus(const char *print_text){
181
 
  int e = errno;
182
 
  fprintf(stderr, "Mandos plugin %s: ",
183
 
          program_invocation_short_name);
184
 
  errno = e;
 
166
  fprintf(stderr, "Mandos plugin %s: ", program_invocation_short_name);
185
167
  perror(print_text);
186
168
}
187
169
 
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
 
 
198
170
/*
199
171
 * Make additional room in "buffer" for at least BUFFER_SIZE more
200
172
 * bytes. "buffer_capacity" is how much is currently allocated,
201
173
 * "buffer_length" is how much is already used.
202
174
 */
203
 
__attribute__((nonnull, warn_unused_result))
204
175
size_t incbuffer(char **buffer, size_t buffer_length,
205
 
                 size_t buffer_capacity){
 
176
                  size_t buffer_capacity){
206
177
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
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;
 
178
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
 
179
    if(buffer == NULL){
213
180
      return 0;
214
181
    }
215
 
    *buffer = new_buf;
216
182
    buffer_capacity += BUFFER_SIZE;
217
183
  }
218
184
  return buffer_capacity;
219
185
}
220
186
 
221
 
/* Add server to set of servers to retry periodically */
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){
 
187
int add_server(const char *ip, uint16_t port,
 
188
                 AvahiIfIndex if_index,
 
189
                 int af){
225
190
  int ret;
226
191
  server *new_server = malloc(sizeof(server));
227
192
  if(new_server == NULL){
228
193
    perror_plus("malloc");
229
 
    return false;
 
194
    return -1;
230
195
  }
231
196
  *new_server = (server){ .ip = strdup(ip),
232
 
                          .port = port,
233
 
                          .if_index = if_index,
234
 
                          .af = af };
 
197
                         .port = port,
 
198
                         .if_index = if_index,
 
199
                         .af = af };
235
200
  if(new_server->ip == NULL){
236
201
    perror_plus("strdup");
237
 
    free(new_server);
238
 
    return false;
239
 
  }
240
 
  ret = clock_gettime(CLOCK_MONOTONIC, &(new_server->last_seen));
241
 
  if(ret == -1){
242
 
    perror_plus("clock_gettime");
243
 
#ifdef __GNUC__
244
 
#pragma GCC diagnostic push
245
 
#pragma GCC diagnostic ignored "-Wcast-qual"
246
 
#endif
247
 
    free((char *)(new_server->ip));
248
 
#ifdef __GNUC__
249
 
#pragma GCC diagnostic pop
250
 
#endif
251
 
    free(new_server);
252
 
    return false;
253
 
  }
254
 
  /* Special case of first server */
255
 
  if(*current_server == NULL){
 
202
    return -1;    
 
203
  }
 
204
  /* uniqe case of first server */
 
205
  if (mc.current_server == NULL){
256
206
    new_server->next = new_server;
257
207
    new_server->prev = new_server;
258
 
    *current_server = new_server;
 
208
    mc.current_server = new_server;
 
209
  /* Placing the new server last in the list */
259
210
  } else {
260
 
    /* Place the new server last in the list */
261
 
    new_server->next = *current_server;
262
 
    new_server->prev = (*current_server)->prev;
 
211
    new_server->next = mc.current_server;
 
212
    new_server->prev = mc.current_server->prev;
263
213
    new_server->prev->next = new_server;
264
 
    (*current_server)->prev = new_server;
265
 
  }
266
 
  return true;
 
214
    mc.current_server->prev = new_server;
 
215
  }
 
216
  ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
 
217
  if(ret == -1){
 
218
    perror_plus("clock_gettime");
 
219
    return -1;
 
220
  }
 
221
  return 0;
267
222
}
268
223
 
269
224
/* 
270
225
 * Initialize GPGME.
271
226
 */
272
 
__attribute__((nonnull, warn_unused_result))
273
 
static bool init_gpgme(const char * const seckey,
274
 
                       const char * const pubkey,
275
 
                       const char * const tempdir,
276
 
                       mandos_context *mc){
 
227
static bool init_gpgme(const char *seckey,
 
228
                       const char *pubkey, const char *tempdir){
277
229
  gpgme_error_t rc;
278
230
  gpgme_engine_info_t engine_info;
279
231
  
 
232
  
280
233
  /*
281
234
   * Helper function to insert pub and seckey to the engine keyring.
282
235
   */
283
 
  bool import_key(const char * const filename){
 
236
  bool import_key(const char *filename){
284
237
    int ret;
285
238
    int fd;
286
239
    gpgme_data_t pgp_data;
293
246
    
294
247
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
295
248
    if(rc != GPG_ERR_NO_ERROR){
296
 
      fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
297
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
249
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
 
250
              gpgme_strsource(rc), gpgme_strerror(rc));
298
251
      return false;
299
252
    }
300
253
    
301
 
    rc = gpgme_op_import(mc->ctx, pgp_data);
 
254
    rc = gpgme_op_import(mc.ctx, pgp_data);
302
255
    if(rc != GPG_ERR_NO_ERROR){
303
 
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
304
 
                   gpgme_strsource(rc), gpgme_strerror(rc));
 
256
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
 
257
              gpgme_strsource(rc), gpgme_strerror(rc));
305
258
      return false;
306
259
    }
307
260
    
308
 
    ret = close(fd);
 
261
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
309
262
    if(ret == -1){
310
263
      perror_plus("close");
311
264
    }
314
267
  }
315
268
  
316
269
  if(debug){
317
 
    fprintf_plus(stderr, "Initializing GPGME\n");
 
270
    fprintf(stderr, "Initializing GPGME\n");
318
271
  }
319
272
  
320
273
  /* Init GPGME */
321
274
  gpgme_check_version(NULL);
322
275
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
323
276
  if(rc != GPG_ERR_NO_ERROR){
324
 
    fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n",
325
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
277
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
 
278
            gpgme_strsource(rc), gpgme_strerror(rc));
326
279
    return false;
327
280
  }
328
281
  
329
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
282
    /* Set GPGME home directory for the OpenPGP engine only */
330
283
  rc = gpgme_get_engine_info(&engine_info);
331
284
  if(rc != GPG_ERR_NO_ERROR){
332
 
    fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n",
333
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
285
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
 
286
            gpgme_strsource(rc), gpgme_strerror(rc));
334
287
    return false;
335
288
  }
336
289
  while(engine_info != NULL){
342
295
    engine_info = engine_info->next;
343
296
  }
344
297
  if(engine_info == NULL){
345
 
    fprintf_plus(stderr, "Could not set GPGME home dir to %s\n",
346
 
                 tempdir);
 
298
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
347
299
    return false;
348
300
  }
349
301
  
350
302
  /* Create new GPGME "context" */
351
 
  rc = gpgme_new(&(mc->ctx));
 
303
  rc = gpgme_new(&(mc.ctx));
352
304
  if(rc != GPG_ERR_NO_ERROR){
353
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
354
 
                 "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
355
 
                 gpgme_strerror(rc));
 
305
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
306
            gpgme_strsource(rc), gpgme_strerror(rc));
356
307
    return false;
357
308
  }
358
309
  
367
318
 * Decrypt OpenPGP data.
368
319
 * Returns -1 on error
369
320
 */
370
 
__attribute__((nonnull, warn_unused_result))
371
321
static ssize_t pgp_packet_decrypt(const char *cryptotext,
372
322
                                  size_t crypto_size,
373
 
                                  char **plaintext,
374
 
                                  mandos_context *mc){
 
323
                                  char **plaintext){
375
324
  gpgme_data_t dh_crypto, dh_plain;
376
325
  gpgme_error_t rc;
377
326
  ssize_t ret;
379
328
  ssize_t plaintext_length = 0;
380
329
  
381
330
  if(debug){
382
 
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
 
331
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
383
332
  }
384
333
  
385
334
  /* Create new GPGME data buffer from memory cryptotext */
386
335
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
387
336
                               0);
388
337
  if(rc != GPG_ERR_NO_ERROR){
389
 
    fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
390
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
338
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
 
339
            gpgme_strsource(rc), gpgme_strerror(rc));
391
340
    return -1;
392
341
  }
393
342
  
394
343
  /* Create new empty GPGME data buffer for the plaintext */
395
344
  rc = gpgme_data_new(&dh_plain);
396
345
  if(rc != GPG_ERR_NO_ERROR){
397
 
    fprintf_plus(stderr, "Mandos plugin mandos-client: "
398
 
                 "bad gpgme_data_new: %s: %s\n",
399
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
346
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
 
347
            gpgme_strsource(rc), gpgme_strerror(rc));
400
348
    gpgme_data_release(dh_crypto);
401
349
    return -1;
402
350
  }
403
351
  
404
352
  /* Decrypt data from the cryptotext data buffer to the plaintext
405
353
     data buffer */
406
 
  rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain);
 
354
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
407
355
  if(rc != GPG_ERR_NO_ERROR){
408
 
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
409
 
                 gpgme_strsource(rc), gpgme_strerror(rc));
 
356
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
357
            gpgme_strsource(rc), gpgme_strerror(rc));
410
358
    plaintext_length = -1;
411
359
    if(debug){
412
360
      gpgme_decrypt_result_t result;
413
 
      result = gpgme_op_decrypt_result(mc->ctx);
 
361
      result = gpgme_op_decrypt_result(mc.ctx);
414
362
      if(result == NULL){
415
 
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
 
363
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
416
364
      } else {
417
 
        fprintf_plus(stderr, "Unsupported algorithm: %s\n",
418
 
                     result->unsupported_algorithm);
419
 
        fprintf_plus(stderr, "Wrong key usage: %u\n",
420
 
                     result->wrong_key_usage);
 
365
        fprintf(stderr, "Unsupported algorithm: %s\n",
 
366
                result->unsupported_algorithm);
 
367
        fprintf(stderr, "Wrong key usage: %u\n",
 
368
                result->wrong_key_usage);
421
369
        if(result->file_name != NULL){
422
 
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
 
370
          fprintf(stderr, "File name: %s\n", result->file_name);
423
371
        }
424
372
        gpgme_recipient_t recipient;
425
373
        recipient = result->recipients;
426
374
        while(recipient != NULL){
427
 
          fprintf_plus(stderr, "Public key algorithm: %s\n",
428
 
                       gpgme_pubkey_algo_name
429
 
                       (recipient->pubkey_algo));
430
 
          fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid);
431
 
          fprintf_plus(stderr, "Secret key available: %s\n",
432
 
                       recipient->status == GPG_ERR_NO_SECKEY
433
 
                       ? "No" : "Yes");
 
375
          fprintf(stderr, "Public key algorithm: %s\n",
 
376
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
 
377
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
378
          fprintf(stderr, "Secret key available: %s\n",
 
379
                  recipient->status == GPG_ERR_NO_SECKEY
 
380
                  ? "No" : "Yes");
434
381
          recipient = recipient->next;
435
382
        }
436
383
      }
439
386
  }
440
387
  
441
388
  if(debug){
442
 
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
 
389
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
443
390
  }
444
391
  
445
392
  /* Seek back to the beginning of the GPGME plaintext data buffer */
452
399
  *plaintext = NULL;
453
400
  while(true){
454
401
    plaintext_capacity = incbuffer(plaintext,
455
 
                                   (size_t)plaintext_length,
456
 
                                   plaintext_capacity);
 
402
                                      (size_t)plaintext_length,
 
403
                                      plaintext_capacity);
457
404
    if(plaintext_capacity == 0){
458
 
      perror_plus("incbuffer");
459
 
      plaintext_length = -1;
460
 
      goto decrypt_end;
 
405
        perror_plus("incbuffer");
 
406
        plaintext_length = -1;
 
407
        goto decrypt_end;
461
408
    }
462
409
    
463
410
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
476
423
  }
477
424
  
478
425
  if(debug){
479
 
    fprintf_plus(stderr, "Decrypted password is: ");
 
426
    fprintf(stderr, "Decrypted password is: ");
480
427
    for(ssize_t i = 0; i < plaintext_length; i++){
481
428
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
482
429
    }
493
440
  return plaintext_length;
494
441
}
495
442
 
496
 
__attribute__((warn_unused_result, const))
497
 
static const char *safe_string(const char *str){
498
 
  if(str == NULL)
499
 
    return "(unknown)";
500
 
  return str;
501
 
}
502
 
 
503
 
__attribute__((warn_unused_result))
504
 
static const char *safer_gnutls_strerror(int value){
505
 
  const char *ret = gnutls_strerror(value);
506
 
  return safe_string(ret);
 
443
static const char * safer_gnutls_strerror(int value){
 
444
  const char *ret = gnutls_strerror(value); /* Spurious warning from
 
445
                                               -Wunreachable-code */
 
446
  if(ret == NULL)
 
447
    ret = "(unknown)";
 
448
  return ret;
507
449
}
508
450
 
509
451
/* GnuTLS log function callback */
510
 
__attribute__((nonnull))
511
452
static void debuggnutls(__attribute__((unused)) int level,
512
453
                        const char* string){
513
 
  fprintf_plus(stderr, "GnuTLS: %s", string);
 
454
  fprintf(stderr, "GnuTLS: %s", string);
514
455
}
515
456
 
516
 
__attribute__((nonnull(1, 2, 4), warn_unused_result))
517
457
static int init_gnutls_global(const char *pubkeyfilename,
518
 
                              const char *seckeyfilename,
519
 
                              const char *dhparamsfilename,
520
 
                              mandos_context *mc){
 
458
                              const char *seckeyfilename){
521
459
  int ret;
522
 
  unsigned int uret;
523
460
  
524
461
  if(debug){
525
 
    fprintf_plus(stderr, "Initializing GnuTLS\n");
 
462
    fprintf(stderr, "Initializing GnuTLS\n");
 
463
  }
 
464
  
 
465
  ret = gnutls_global_init();
 
466
  if(ret != GNUTLS_E_SUCCESS){
 
467
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
468
            safer_gnutls_strerror(ret));
 
469
    return -1;
526
470
  }
527
471
  
528
472
  if(debug){
534
478
  }
535
479
  
536
480
  /* OpenPGP credentials */
537
 
  ret = gnutls_certificate_allocate_credentials(&mc->cred);
 
481
  gnutls_certificate_allocate_credentials(&mc.cred);
538
482
  if(ret != GNUTLS_E_SUCCESS){
539
 
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
540
 
                 safer_gnutls_strerror(ret));
 
483
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
484
                                                    from
 
485
                                                    -Wunreachable-code
 
486
                                                 */
 
487
            safer_gnutls_strerror(ret));
 
488
    gnutls_global_deinit();
541
489
    return -1;
542
490
  }
543
491
  
544
492
  if(debug){
545
 
    fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and"
546
 
                 " secret key %s as GnuTLS credentials\n",
547
 
                 pubkeyfilename,
548
 
                 seckeyfilename);
 
493
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
 
494
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
 
495
            seckeyfilename);
549
496
  }
550
497
  
551
498
  ret = gnutls_certificate_set_openpgp_key_file
552
 
    (mc->cred, pubkeyfilename, seckeyfilename,
 
499
    (mc.cred, pubkeyfilename, seckeyfilename,
553
500
     GNUTLS_OPENPGP_FMT_BASE64);
554
501
  if(ret != GNUTLS_E_SUCCESS){
555
 
    fprintf_plus(stderr,
556
 
                 "Error[%d] while reading the OpenPGP key pair ('%s',"
557
 
                 " '%s')\n", ret, pubkeyfilename, seckeyfilename);
558
 
    fprintf_plus(stderr, "The GnuTLS error is: %s\n",
559
 
                 safer_gnutls_strerror(ret));
 
502
    fprintf(stderr,
 
503
            "Error[%d] while reading the OpenPGP key pair ('%s',"
 
504
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
 
505
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
506
            safer_gnutls_strerror(ret));
560
507
    goto globalfail;
561
508
  }
562
509
  
563
510
  /* GnuTLS server initialization */
564
 
  ret = gnutls_dh_params_init(&mc->dh_params);
565
 
  if(ret != GNUTLS_E_SUCCESS){
566
 
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
567
 
                 " initialization: %s\n",
568
 
                 safer_gnutls_strerror(ret));
569
 
    goto globalfail;
570
 
  }
571
 
  /* If a Diffie-Hellman parameters file was given, try to use it */
572
 
  if(dhparamsfilename != NULL){
573
 
    gnutls_datum_t params = { .data = NULL, .size = 0 };
574
 
    do {
575
 
      int dhpfile = open(dhparamsfilename, O_RDONLY);
576
 
      if(dhpfile == -1){
577
 
        perror_plus("open");
578
 
        dhparamsfilename = NULL;
579
 
        break;
580
 
      }
581
 
      size_t params_capacity = 0;
582
 
      while(true){
583
 
        params_capacity = incbuffer((char **)&params.data,
584
 
                                    (size_t)params.size,
585
 
                                    (size_t)params_capacity);
586
 
        if(params_capacity == 0){
587
 
          perror_plus("incbuffer");
588
 
          free(params.data);
589
 
          params.data = NULL;
590
 
          dhparamsfilename = NULL;
591
 
          break;
592
 
        }
593
 
        ssize_t bytes_read = read(dhpfile,
594
 
                                  params.data + params.size,
595
 
                                  BUFFER_SIZE);
596
 
        /* EOF */
597
 
        if(bytes_read == 0){
598
 
          break;
599
 
        }
600
 
        /* check bytes_read for failure */
601
 
        if(bytes_read < 0){
602
 
          perror_plus("read");
603
 
          free(params.data);
604
 
          params.data = NULL;
605
 
          dhparamsfilename = NULL;
606
 
          break;
607
 
        }
608
 
        params.size += (unsigned int)bytes_read;
609
 
      }
610
 
      if(params.data == NULL){
611
 
        dhparamsfilename = NULL;
612
 
      }
613
 
      if(dhparamsfilename == NULL){
614
 
        break;
615
 
      }
616
 
      ret = gnutls_dh_params_import_pkcs3(mc->dh_params, &params,
617
 
                                          GNUTLS_X509_FMT_PEM);
618
 
      if(ret != GNUTLS_E_SUCCESS){
619
 
        fprintf_plus(stderr, "Failed to parse DH parameters in file"
620
 
                     " \"%s\": %s\n", dhparamsfilename,
621
 
                     safer_gnutls_strerror(ret));
622
 
        dhparamsfilename = NULL;
623
 
      }
624
 
    } while(false);
625
 
  }
626
 
  if(dhparamsfilename == NULL){
627
 
    if(mc->dh_bits == 0){
628
 
      /* Find out the optimal number of DH bits */
629
 
      /* Try to read the private key file */
630
 
      gnutls_datum_t buffer = { .data = NULL, .size = 0 };
631
 
      do {
632
 
        int secfile = open(seckeyfilename, O_RDONLY);
633
 
        if(secfile == -1){
634
 
          perror_plus("open");
635
 
          break;
636
 
        }
637
 
        size_t buffer_capacity = 0;
638
 
        while(true){
639
 
          buffer_capacity = incbuffer((char **)&buffer.data,
640
 
                                      (size_t)buffer.size,
641
 
                                      (size_t)buffer_capacity);
642
 
          if(buffer_capacity == 0){
643
 
            perror_plus("incbuffer");
644
 
            free(buffer.data);
645
 
            buffer.data = NULL;
646
 
            break;
647
 
          }
648
 
          ssize_t bytes_read = read(secfile,
649
 
                                    buffer.data + buffer.size,
650
 
                                    BUFFER_SIZE);
651
 
          /* EOF */
652
 
          if(bytes_read == 0){
653
 
            break;
654
 
          }
655
 
          /* check bytes_read for failure */
656
 
          if(bytes_read < 0){
657
 
            perror_plus("read");
658
 
            free(buffer.data);
659
 
            buffer.data = NULL;
660
 
            break;
661
 
          }
662
 
          buffer.size += (unsigned int)bytes_read;
663
 
        }
664
 
        close(secfile);
665
 
      } while(false);
666
 
      /* If successful, use buffer to parse private key */
667
 
      gnutls_sec_param_t sec_param = GNUTLS_SEC_PARAM_ULTRA;
668
 
      if(buffer.data != NULL){
669
 
        {
670
 
          gnutls_openpgp_privkey_t privkey = NULL;
671
 
          ret = gnutls_openpgp_privkey_init(&privkey);
672
 
          if(ret != GNUTLS_E_SUCCESS){
673
 
            fprintf_plus(stderr, "Error initializing OpenPGP key"
674
 
                         " structure: %s",
675
 
                         safer_gnutls_strerror(ret));
676
 
            free(buffer.data);
677
 
            buffer.data = NULL;
678
 
          } else {
679
 
            ret = gnutls_openpgp_privkey_import
680
 
              (privkey, &buffer, GNUTLS_OPENPGP_FMT_BASE64, "", 0);
681
 
            if(ret != GNUTLS_E_SUCCESS){
682
 
              fprintf_plus(stderr, "Error importing OpenPGP key : %s",
683
 
                           safer_gnutls_strerror(ret));
684
 
              privkey = NULL;
685
 
            }
686
 
            free(buffer.data);
687
 
            buffer.data = NULL;
688
 
            if(privkey != NULL){
689
 
              /* Use private key to suggest an appropriate
690
 
                 sec_param */
691
 
              sec_param = gnutls_openpgp_privkey_sec_param(privkey);
692
 
              gnutls_openpgp_privkey_deinit(privkey);
693
 
              if(debug){
694
 
                fprintf_plus(stderr, "This OpenPGP key implies using"
695
 
                             " a GnuTLS security parameter \"%s\".\n",
696
 
                             safe_string(gnutls_sec_param_get_name
697
 
                                         (sec_param)));
698
 
              }
699
 
            }
700
 
          }
701
 
        }
702
 
        if(sec_param == GNUTLS_SEC_PARAM_UNKNOWN){
703
 
          /* Err on the side of caution */
704
 
          sec_param = GNUTLS_SEC_PARAM_ULTRA;
705
 
          if(debug){
706
 
            fprintf_plus(stderr, "Falling back to security parameter"
707
 
                         " \"%s\"\n",
708
 
                         safe_string(gnutls_sec_param_get_name
709
 
                                     (sec_param)));
710
 
          }
711
 
        }
712
 
      }
713
 
      uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param);
714
 
      if(uret != 0){
715
 
        mc->dh_bits = uret;
716
 
        if(debug){
717
 
          fprintf_plus(stderr, "A \"%s\" GnuTLS security parameter"
718
 
                       " implies %u DH bits; using that.\n",
719
 
                       safe_string(gnutls_sec_param_get_name
720
 
                                   (sec_param)),
721
 
                       mc->dh_bits);
722
 
        }
723
 
      } else {
724
 
        fprintf_plus(stderr, "Failed to get implied number of DH"
725
 
                     " bits for security parameter \"%s\"): %s\n",
726
 
                     safe_string(gnutls_sec_param_get_name
727
 
                                 (sec_param)),
728
 
                     safer_gnutls_strerror(ret));
729
 
        goto globalfail;
730
 
      }
731
 
    } else if(debug){
732
 
      fprintf_plus(stderr, "DH bits explicitly set to %u\n",
733
 
                   mc->dh_bits);
734
 
    }
735
 
    ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits);
736
 
    if(ret != GNUTLS_E_SUCCESS){
737
 
      fprintf_plus(stderr, "Error in GnuTLS prime generation (%u"
738
 
                   " bits): %s\n", mc->dh_bits,
739
 
                   safer_gnutls_strerror(ret));
740
 
      goto globalfail;
741
 
    }
742
 
  }
743
 
  gnutls_certificate_set_dh_params(mc->cred, mc->dh_params);
 
511
  ret = gnutls_dh_params_init(&mc.dh_params);
 
512
  if(ret != GNUTLS_E_SUCCESS){
 
513
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
 
514
            " %s\n", safer_gnutls_strerror(ret));
 
515
    goto globalfail;
 
516
  }
 
517
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
 
518
  if(ret != GNUTLS_E_SUCCESS){
 
519
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
 
520
            safer_gnutls_strerror(ret));
 
521
    goto globalfail;
 
522
  }
 
523
  
 
524
  gnutls_certificate_set_dh_params(mc.cred, mc.dh_params);
744
525
  
745
526
  return 0;
746
527
  
747
528
 globalfail:
748
529
  
749
 
  gnutls_certificate_free_credentials(mc->cred);
750
 
  gnutls_dh_params_deinit(mc->dh_params);
 
530
  gnutls_certificate_free_credentials(mc.cred);
 
531
  gnutls_global_deinit();
 
532
  gnutls_dh_params_deinit(mc.dh_params);
751
533
  return -1;
752
534
}
753
535
 
754
 
__attribute__((nonnull, warn_unused_result))
755
 
static int init_gnutls_session(gnutls_session_t *session,
756
 
                               mandos_context *mc){
 
536
static int init_gnutls_session(gnutls_session_t *session){
757
537
  int ret;
758
538
  /* GnuTLS session creation */
759
539
  do {
763
543
    }
764
544
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
765
545
  if(ret != GNUTLS_E_SUCCESS){
766
 
    fprintf_plus(stderr,
767
 
                 "Error in GnuTLS session initialization: %s\n",
768
 
                 safer_gnutls_strerror(ret));
 
546
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
 
547
            safer_gnutls_strerror(ret));
769
548
  }
770
549
  
771
550
  {
772
551
    const char *err;
773
552
    do {
774
 
      ret = gnutls_priority_set_direct(*session, mc->priority, &err);
 
553
      ret = gnutls_priority_set_direct(*session, mc.priority, &err);
775
554
      if(quit_now){
776
555
        gnutls_deinit(*session);
777
556
        return -1;
778
557
      }
779
558
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
780
559
    if(ret != GNUTLS_E_SUCCESS){
781
 
      fprintf_plus(stderr, "Syntax error at: %s\n", err);
782
 
      fprintf_plus(stderr, "GnuTLS error: %s\n",
783
 
                   safer_gnutls_strerror(ret));
 
560
      fprintf(stderr, "Syntax error at: %s\n", err);
 
561
      fprintf(stderr, "GnuTLS error: %s\n",
 
562
              safer_gnutls_strerror(ret));
784
563
      gnutls_deinit(*session);
785
564
      return -1;
786
565
    }
788
567
  
789
568
  do {
790
569
    ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE,
791
 
                                 mc->cred);
 
570
                                 mc.cred);
792
571
    if(quit_now){
793
572
      gnutls_deinit(*session);
794
573
      return -1;
795
574
    }
796
575
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
797
576
  if(ret != GNUTLS_E_SUCCESS){
798
 
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
799
 
                 safer_gnutls_strerror(ret));
 
577
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
 
578
            safer_gnutls_strerror(ret));
800
579
    gnutls_deinit(*session);
801
580
    return -1;
802
581
  }
804
583
  /* ignore client certificate if any. */
805
584
  gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE);
806
585
  
 
586
  gnutls_dh_set_prime_bits(*session, mc.dh_bits);
 
587
  
807
588
  return 0;
808
589
}
809
590
 
811
592
static void empty_log(__attribute__((unused)) AvahiLogLevel level,
812
593
                      __attribute__((unused)) const char *txt){}
813
594
 
814
 
/* Set effective uid to 0, return errno */
815
 
__attribute__((warn_unused_result))
816
 
error_t raise_privileges(void){
817
 
  error_t old_errno = errno;
818
 
  error_t ret_errno = 0;
819
 
  if(seteuid(0) == -1){
820
 
    ret_errno = errno;
821
 
  }
822
 
  errno = old_errno;
823
 
  return ret_errno;
824
 
}
825
 
 
826
 
/* Set effective and real user ID to 0.  Return errno. */
827
 
__attribute__((warn_unused_result))
828
 
error_t raise_privileges_permanently(void){
829
 
  error_t old_errno = errno;
830
 
  error_t ret_errno = raise_privileges();
831
 
  if(ret_errno != 0){
832
 
    errno = old_errno;
833
 
    return ret_errno;
834
 
  }
835
 
  if(setuid(0) == -1){
836
 
    ret_errno = errno;
837
 
  }
838
 
  errno = old_errno;
839
 
  return ret_errno;
840
 
}
841
 
 
842
 
/* Set effective user ID to unprivileged saved user ID */
843
 
__attribute__((warn_unused_result))
844
 
error_t lower_privileges(void){
845
 
  error_t old_errno = errno;
846
 
  error_t ret_errno = 0;
847
 
  if(seteuid(uid) == -1){
848
 
    ret_errno = errno;
849
 
  }
850
 
  errno = old_errno;
851
 
  return ret_errno;
852
 
}
853
 
 
854
 
/* Lower privileges permanently */
855
 
__attribute__((warn_unused_result))
856
 
error_t lower_privileges_permanently(void){
857
 
  error_t old_errno = errno;
858
 
  error_t ret_errno = 0;
859
 
  if(setuid(uid) == -1){
860
 
    ret_errno = errno;
861
 
  }
862
 
  errno = old_errno;
863
 
  return ret_errno;
864
 
}
865
 
 
866
 
/* Helper function to add_local_route() and delete_local_route() */
867
 
__attribute__((nonnull, warn_unused_result))
868
 
static bool add_delete_local_route(const bool add,
869
 
                                   const char *address,
870
 
                                   AvahiIfIndex if_index){
871
 
  int ret;
872
 
  char helper[] = "mandos-client-iprouteadddel";
873
 
  char add_arg[] = "add";
874
 
  char delete_arg[] = "delete";
875
 
  char debug_flag[] = "--debug";
876
 
  char *pluginhelperdir = getenv("MANDOSPLUGINHELPERDIR");
877
 
  if(pluginhelperdir == NULL){
878
 
    if(debug){
879
 
      fprintf_plus(stderr, "MANDOSPLUGINHELPERDIR environment"
880
 
                   " variable not set; cannot run helper\n");
881
 
    }
882
 
    return false;
883
 
  }
884
 
  
885
 
  char interface[IF_NAMESIZE];
886
 
  if(if_indextoname((unsigned int)if_index, interface) == NULL){
887
 
    perror_plus("if_indextoname");
888
 
    return false;
889
 
  }
890
 
  
891
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
892
 
  if(devnull == -1){
893
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
894
 
    return false;
895
 
  }
896
 
  pid_t pid = fork();
897
 
  if(pid == 0){
898
 
    /* Child */
899
 
    /* Raise privileges */
900
 
    errno = raise_privileges_permanently();
901
 
    if(errno != 0){
902
 
      perror_plus("Failed to raise privileges");
903
 
      /* _exit(EX_NOPERM); */
904
 
    } else {
905
 
      /* Set group */
906
 
      errno = 0;
907
 
      ret = setgid(0);
908
 
      if(ret == -1){
909
 
        perror_plus("setgid");
910
 
        _exit(EX_NOPERM);
911
 
      }
912
 
      /* Reset supplementary groups */
913
 
      errno = 0;
914
 
      ret = setgroups(0, NULL);
915
 
      if(ret == -1){
916
 
        perror_plus("setgroups");
917
 
        _exit(EX_NOPERM);
918
 
      }
919
 
    }
920
 
    ret = dup2(devnull, STDIN_FILENO);
921
 
    if(ret == -1){
922
 
      perror_plus("dup2(devnull, STDIN_FILENO)");
923
 
      _exit(EX_OSERR);
924
 
    }
925
 
    ret = close(devnull);
926
 
    if(ret == -1){
927
 
      perror_plus("close");
928
 
      _exit(EX_OSERR);
929
 
    }
930
 
    ret = dup2(STDERR_FILENO, STDOUT_FILENO);
931
 
    if(ret == -1){
932
 
      perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
933
 
      _exit(EX_OSERR);
934
 
    }
935
 
    int helperdir_fd = (int)TEMP_FAILURE_RETRY(open(pluginhelperdir,
936
 
                                                    O_RDONLY
937
 
                                                    | O_DIRECTORY
938
 
                                                    | O_PATH
939
 
                                                    | O_CLOEXEC));
940
 
    if(helperdir_fd == -1){
941
 
      perror_plus("open");
942
 
      _exit(EX_UNAVAILABLE);
943
 
    }
944
 
    int helper_fd = (int)TEMP_FAILURE_RETRY(openat(helperdir_fd,
945
 
                                                   helper, O_RDONLY));
946
 
    if(helper_fd == -1){
947
 
      perror_plus("openat");
948
 
      close(helperdir_fd);
949
 
      _exit(EX_UNAVAILABLE);
950
 
    }
951
 
    close(helperdir_fd);
952
 
#ifdef __GNUC__
953
 
#pragma GCC diagnostic push
954
 
#pragma GCC diagnostic ignored "-Wcast-qual"
955
 
#endif
956
 
    if(fexecve(helper_fd, (char *const [])
957
 
               { helper, add ? add_arg : delete_arg, (char *)address,
958
 
                   interface, debug ? debug_flag : NULL, NULL },
959
 
               environ) == -1){
960
 
#ifdef __GNUC__
961
 
#pragma GCC diagnostic pop
962
 
#endif
963
 
      perror_plus("fexecve");
964
 
      _exit(EXIT_FAILURE);
965
 
    }
966
 
  }
967
 
  if(pid == -1){
968
 
    perror_plus("fork");
969
 
    return false;
970
 
  }
971
 
  int status;
972
 
  pid_t pret = -1;
973
 
  errno = 0;
974
 
  do {
975
 
    pret = waitpid(pid, &status, 0);
976
 
    if(pret == -1 and errno == EINTR and quit_now){
977
 
      int errno_raising = 0;
978
 
      if((errno = raise_privileges()) != 0){
979
 
        errno_raising = errno;
980
 
        perror_plus("Failed to raise privileges in order to"
981
 
                    " kill helper program");
982
 
      }
983
 
      if(kill(pid, SIGTERM) == -1){
984
 
        perror_plus("kill");
985
 
      }
986
 
      if((errno_raising == 0) and (errno = lower_privileges()) != 0){
987
 
        perror_plus("Failed to lower privileges after killing"
988
 
                    " helper program");
989
 
      }
990
 
      return false;
991
 
    }
992
 
  } while(pret == -1 and errno == EINTR);
993
 
  if(pret == -1){
994
 
    perror_plus("waitpid");
995
 
    return false;
996
 
  }
997
 
  if(WIFEXITED(status)){
998
 
    if(WEXITSTATUS(status) != 0){
999
 
      fprintf_plus(stderr, "Error: iprouteadddel exited"
1000
 
                   " with status %d\n", WEXITSTATUS(status));
1001
 
      return false;
1002
 
    }
1003
 
    return true;
1004
 
  }
1005
 
  if(WIFSIGNALED(status)){
1006
 
    fprintf_plus(stderr, "Error: iprouteadddel died by"
1007
 
                 " signal %d\n", WTERMSIG(status));
1008
 
    return false;
1009
 
  }
1010
 
  fprintf_plus(stderr, "Error: iprouteadddel crashed\n");
1011
 
  return false;
1012
 
}
1013
 
 
1014
 
__attribute__((nonnull, warn_unused_result))
1015
 
static bool add_local_route(const char *address,
1016
 
                            AvahiIfIndex if_index){
1017
 
  if(debug){
1018
 
    fprintf_plus(stderr, "Adding route to %s\n", address);
1019
 
  }
1020
 
  return add_delete_local_route(true, address, if_index);
1021
 
}
1022
 
 
1023
 
__attribute__((nonnull, warn_unused_result))
1024
 
static bool delete_local_route(const char *address,
1025
 
                               AvahiIfIndex if_index){
1026
 
  if(debug){
1027
 
    fprintf_plus(stderr, "Removing route to %s\n", address);
1028
 
  }
1029
 
  return add_delete_local_route(false, address, if_index);
1030
 
}
1031
 
 
1032
595
/* Called when a Mandos server is found */
1033
 
__attribute__((nonnull, warn_unused_result))
1034
 
static int start_mandos_communication(const char *ip, in_port_t port,
 
596
static int start_mandos_communication(const char *ip, uint16_t port,
1035
597
                                      AvahiIfIndex if_index,
1036
 
                                      int af, mandos_context *mc){
 
598
                                      int af){
1037
599
  int ret, tcp_sd = -1;
1038
600
  ssize_t sret;
1039
 
  struct sockaddr_storage to;
 
601
  union {
 
602
    struct sockaddr_in in;
 
603
    struct sockaddr_in6 in6;
 
604
  } to;
1040
605
  char *buffer = NULL;
1041
606
  char *decrypted_buffer = NULL;
1042
607
  size_t buffer_length = 0;
1045
610
  int retval = -1;
1046
611
  gnutls_session_t session;
1047
612
  int pf;                       /* Protocol family */
1048
 
  bool route_added = false;
1049
613
  
1050
614
  errno = 0;
1051
615
  
1062
626
    pf = PF_INET;
1063
627
    break;
1064
628
  default:
1065
 
    fprintf_plus(stderr, "Bad address family: %d\n", af);
 
629
    fprintf(stderr, "Bad address family: %d\n", af);
1066
630
    errno = EINVAL;
1067
631
    return -1;
1068
632
  }
1069
633
  
1070
 
  /* If the interface is specified and we have a list of interfaces */
1071
 
  if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){
1072
 
    /* Check if the interface is one of the interfaces we are using */
1073
 
    bool match = false;
1074
 
    {
1075
 
      char *interface = NULL;
1076
 
      while((interface=argz_next(mc->interfaces, mc->interfaces_size,
1077
 
                                 interface))){
1078
 
        if(if_nametoindex(interface) == (unsigned int)if_index){
1079
 
          match = true;
1080
 
          break;
1081
 
        }
1082
 
      }
1083
 
    }
1084
 
    if(not match){
1085
 
      /* This interface does not match any in the list, so we don't
1086
 
         connect to the server */
1087
 
      if(debug){
1088
 
        char interface[IF_NAMESIZE];
1089
 
        if(if_indextoname((unsigned int)if_index, interface) == NULL){
1090
 
          perror_plus("if_indextoname");
1091
 
        } else {
1092
 
          fprintf_plus(stderr, "Skipping server on non-used interface"
1093
 
                       " \"%s\"\n",
1094
 
                       if_indextoname((unsigned int)if_index,
1095
 
                                      interface));
1096
 
        }
1097
 
      }
1098
 
      return -1;
1099
 
    }
1100
 
  }
1101
 
  
1102
 
  ret = init_gnutls_session(&session, mc);
 
634
  ret = init_gnutls_session(&session);
1103
635
  if(ret != 0){
1104
636
    return -1;
1105
637
  }
1106
638
  
1107
639
  if(debug){
1108
 
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
1109
 
                 PRIuMAX "\n", ip, (uintmax_t)port);
 
640
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
 
641
            "\n", ip, port);
1110
642
  }
1111
643
  
1112
 
  tcp_sd = socket(pf, SOCK_STREAM | SOCK_CLOEXEC, 0);
 
644
  tcp_sd = socket(pf, SOCK_STREAM, 0);
1113
645
  if(tcp_sd < 0){
1114
646
    int e = errno;
1115
647
    perror_plus("socket");
1122
654
    goto mandos_end;
1123
655
  }
1124
656
  
 
657
  memset(&to, 0, sizeof(to));
1125
658
  if(af == AF_INET6){
1126
 
    struct sockaddr_in6 *to6 = (struct sockaddr_in6 *)&to;
1127
 
    *to6 = (struct sockaddr_in6){ .sin6_family = (sa_family_t)af };
1128
 
    ret = inet_pton(af, ip, &to6->sin6_addr);
 
659
    to.in6.sin6_family = (sa_family_t)af;
 
660
    ret = inet_pton(af, ip, &to.in6.sin6_addr);
1129
661
  } else {                      /* IPv4 */
1130
 
    struct sockaddr_in *to4 = (struct sockaddr_in *)&to;
1131
 
    *to4 = (struct sockaddr_in){ .sin_family = (sa_family_t)af };
1132
 
    ret = inet_pton(af, ip, &to4->sin_addr);
 
662
    to.in.sin_family = (sa_family_t)af;
 
663
    ret = inet_pton(af, ip, &to.in.sin_addr);
1133
664
  }
1134
665
  if(ret < 0 ){
1135
666
    int e = errno;
1139
670
  }
1140
671
  if(ret == 0){
1141
672
    int e = errno;
1142
 
    fprintf_plus(stderr, "Bad address: %s\n", ip);
 
673
    fprintf(stderr, "Bad address: %s\n", ip);
1143
674
    errno = e;
1144
675
    goto mandos_end;
1145
676
  }
1146
677
  if(af == AF_INET6){
1147
 
    ((struct sockaddr_in6 *)&to)->sin6_port = htons(port);
1148
 
    if(IN6_IS_ADDR_LINKLOCAL
1149
 
       (&((struct sockaddr_in6 *)&to)->sin6_addr)){
 
678
    to.in6.sin6_port = htons(port); /* Spurious warnings from
 
679
                                       -Wconversion and
 
680
                                       -Wunreachable-code */
 
681
    
 
682
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
 
683
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
 
684
                              -Wunreachable-code*/
1150
685
      if(if_index == AVAHI_IF_UNSPEC){
1151
 
        fprintf_plus(stderr, "An IPv6 link-local address is"
1152
 
                     " incomplete without a network interface\n");
 
686
        fprintf(stderr, "An IPv6 link-local address is incomplete"
 
687
                " without a network interface\n");
1153
688
        errno = EINVAL;
1154
689
        goto mandos_end;
1155
690
      }
1156
691
      /* Set the network interface number as scope */
1157
 
      ((struct sockaddr_in6 *)&to)->sin6_scope_id = (uint32_t)if_index;
 
692
      to.in6.sin6_scope_id = (uint32_t)if_index;
1158
693
    }
1159
694
  } else {
1160
 
    ((struct sockaddr_in *)&to)->sin_port = htons(port);
 
695
    to.in.sin_port = htons(port); /* Spurious warnings from
 
696
                                     -Wconversion and
 
697
                                     -Wunreachable-code */
1161
698
  }
1162
699
  
1163
700
  if(quit_now){
1171
708
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
1172
709
        perror_plus("if_indextoname");
1173
710
      } else {
1174
 
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX
1175
 
                     "\n", ip, interface, (uintmax_t)port);
 
711
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
 
712
                ip, interface, port);
1176
713
      }
1177
714
    } else {
1178
 
      fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n",
1179
 
                   ip, (uintmax_t)port);
 
715
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
716
              port);
1180
717
    }
1181
718
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
1182
719
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
1183
 
    if(af == AF_INET6){
1184
 
      ret = getnameinfo((struct sockaddr *)&to,
1185
 
                        sizeof(struct sockaddr_in6),
1186
 
                        addrstr, sizeof(addrstr), NULL, 0,
1187
 
                        NI_NUMERICHOST);
1188
 
    } else {
1189
 
      ret = getnameinfo((struct sockaddr *)&to,
1190
 
                        sizeof(struct sockaddr_in),
1191
 
                        addrstr, sizeof(addrstr), NULL, 0,
1192
 
                        NI_NUMERICHOST);
1193
 
    }
1194
 
    if(ret == EAI_SYSTEM){
1195
 
      perror_plus("getnameinfo");
1196
 
    } else if(ret != 0) {
1197
 
      fprintf_plus(stderr, "getnameinfo: %s", gai_strerror(ret));
1198
 
    } else if(strcmp(addrstr, ip) != 0){
1199
 
      fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
1200
 
    }
1201
 
  }
1202
 
  
1203
 
  if(quit_now){
1204
 
    errno = EINTR;
1205
 
    goto mandos_end;
1206
 
  }
1207
 
  
1208
 
  while(true){
1209
 
    if(af == AF_INET6){
1210
 
      ret = connect(tcp_sd, (struct sockaddr *)&to,
1211
 
                    sizeof(struct sockaddr_in6));
1212
 
    } else {
1213
 
      ret = connect(tcp_sd, (struct sockaddr *)&to, /* IPv4 */
1214
 
                    sizeof(struct sockaddr_in));
1215
 
    }
1216
 
    if(ret < 0){
1217
 
      if(((errno == ENETUNREACH) or (errno == EHOSTUNREACH))
1218
 
         and if_index != AVAHI_IF_UNSPEC
1219
 
         and connect_to == NULL
1220
 
         and not route_added and
1221
 
         ((af == AF_INET6 and not
1222
 
           IN6_IS_ADDR_LINKLOCAL(&(((struct sockaddr_in6 *)
1223
 
                                    &to)->sin6_addr)))
1224
 
          or (af == AF_INET and
1225
 
              /* Not a a IPv4LL address */
1226
 
              (ntohl(((struct sockaddr_in *)&to)->sin_addr.s_addr)
1227
 
               & 0xFFFF0000L) != 0xA9FE0000L))){
1228
 
        /* Work around Avahi bug - Avahi does not announce link-local
1229
 
           addresses if it has a global address, so local hosts with
1230
 
           *only* a link-local address (e.g. Mandos clients) cannot
1231
 
           connect to a Mandos server announced by Avahi on a server
1232
 
           host with a global address.  Work around this by retrying
1233
 
           with an explicit route added with the server's address.
1234
 
           
1235
 
           Avahi bug reference:
1236
 
           http://lists.freedesktop.org/archives/avahi/2010-February/001833.html
1237
 
           https://bugs.debian.org/587961
1238
 
        */
1239
 
        if(debug){
1240
 
          fprintf_plus(stderr, "Mandos server unreachable, trying"
1241
 
                       " direct route\n");
1242
 
        }
1243
 
        int e = errno;
1244
 
        route_added = add_local_route(ip, if_index);
1245
 
        if(route_added){
1246
 
          continue;
1247
 
        }
1248
 
        errno = e;
1249
 
      }
1250
 
      if(errno != ECONNREFUSED or debug){
1251
 
        int e = errno;
1252
 
        perror_plus("connect");
1253
 
        errno = e;
1254
 
      }
1255
 
      goto mandos_end;
1256
 
    }
1257
 
    
1258
 
    if(quit_now){
1259
 
      errno = EINTR;
1260
 
      goto mandos_end;
1261
 
    }
1262
 
    break;
 
720
    const char *pcret;
 
721
    if(af == AF_INET6){
 
722
      pcret = inet_ntop(af, &(to.in6.sin6_addr), addrstr,
 
723
                        sizeof(addrstr));
 
724
    } else {
 
725
      pcret = inet_ntop(af, &(to.in.sin_addr), addrstr,
 
726
                        sizeof(addrstr));
 
727
    }
 
728
    if(pcret == NULL){
 
729
      perror_plus("inet_ntop");
 
730
    } else {
 
731
      if(strcmp(addrstr, ip) != 0){
 
732
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
733
      }
 
734
    }
 
735
  }
 
736
  
 
737
  if(quit_now){
 
738
    errno = EINTR;
 
739
    goto mandos_end;
 
740
  }
 
741
  
 
742
  if(af == AF_INET6){
 
743
    ret = connect(tcp_sd, &to.in6, sizeof(to));
 
744
  } else {
 
745
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
 
746
  }
 
747
  if(ret < 0){
 
748
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
 
749
      int e = errno;
 
750
      perror_plus("connect");
 
751
      errno = e;
 
752
    }
 
753
    goto mandos_end;
 
754
  }
 
755
  
 
756
  if(quit_now){
 
757
    errno = EINTR;
 
758
    goto mandos_end;
1263
759
  }
1264
760
  
1265
761
  const char *out = mandos_protocol_version;
1267
763
  while(true){
1268
764
    size_t out_size = strlen(out);
1269
765
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
1270
 
                                        out_size - written));
 
766
                                   out_size - written));
1271
767
    if(ret == -1){
1272
768
      int e = errno;
1273
769
      perror_plus("write");
1293
789
  }
1294
790
  
1295
791
  if(debug){
1296
 
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
 
792
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
1297
793
  }
1298
794
  
1299
795
  if(quit_now){
1300
796
    errno = EINTR;
1301
797
    goto mandos_end;
1302
798
  }
1303
 
  
1304
 
  /* This casting via intptr_t is to eliminate warning about casting
1305
 
     an int to a pointer type.  This is exactly how the GnuTLS Guile
1306
 
     function "set-session-transport-fd!" does it. */
1307
 
  gnutls_transport_set_ptr(session,
1308
 
                           (gnutls_transport_ptr_t)(intptr_t)tcp_sd);
 
799
 
 
800
  /* Spurious warnings from -Wint-to-pointer-cast */
 
801
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
1309
802
  
1310
803
  if(quit_now){
1311
804
    errno = EINTR;
1322
815
  
1323
816
  if(ret != GNUTLS_E_SUCCESS){
1324
817
    if(debug){
1325
 
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
 
818
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
1326
819
      gnutls_perror(ret);
1327
820
    }
1328
821
    errno = EPROTO;
1332
825
  /* Read OpenPGP packet that contains the wanted password */
1333
826
  
1334
827
  if(debug){
1335
 
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
1336
 
                 " %s\n", ip);
 
828
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
829
            ip);
1337
830
  }
1338
831
  
1339
832
  while(true){
1344
837
    }
1345
838
    
1346
839
    buffer_capacity = incbuffer(&buffer, buffer_length,
1347
 
                                buffer_capacity);
 
840
                                   buffer_capacity);
1348
841
    if(buffer_capacity == 0){
1349
842
      int e = errno;
1350
843
      perror_plus("incbuffer");
1377
870
          }
1378
871
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
1379
872
        if(ret < 0){
1380
 
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
1381
 
                       "***\n");
 
873
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
1382
874
          gnutls_perror(ret);
1383
875
          errno = EPROTO;
1384
876
          goto mandos_end;
1385
877
        }
1386
878
        break;
1387
879
      default:
1388
 
        fprintf_plus(stderr, "Unknown error while reading data from"
1389
 
                     " encrypted session with Mandos server\n");
 
880
        fprintf(stderr, "Unknown error while reading data from"
 
881
                " encrypted session with Mandos server\n");
1390
882
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
1391
883
        errno = EIO;
1392
884
        goto mandos_end;
1397
889
  }
1398
890
  
1399
891
  if(debug){
1400
 
    fprintf_plus(stderr, "Closing TLS session\n");
 
892
    fprintf(stderr, "Closing TLS session\n");
1401
893
  }
1402
894
  
1403
895
  if(quit_now){
1415
907
  
1416
908
  if(buffer_length > 0){
1417
909
    ssize_t decrypted_buffer_size;
1418
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
1419
 
                                               &decrypted_buffer, mc);
 
910
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
911
                                               buffer_length,
 
912
                                               &decrypted_buffer);
1420
913
    if(decrypted_buffer_size >= 0){
1421
914
      
1422
915
      written = 0;
1432
925
        if(ret == 0 and ferror(stdout)){
1433
926
          int e = errno;
1434
927
          if(debug){
1435
 
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
1436
 
                         strerror(errno));
 
928
            fprintf(stderr, "Error writing encrypted data: %s\n",
 
929
                    strerror(errno));
1437
930
          }
1438
931
          errno = e;
1439
932
          goto mandos_end;
1448
941
  
1449
942
 mandos_end:
1450
943
  {
1451
 
    if(route_added){
1452
 
      if(not delete_local_route(ip, if_index)){
1453
 
        fprintf_plus(stderr, "Failed to delete local route to %s on"
1454
 
                     " interface %d", ip, if_index);
1455
 
      }
1456
 
    }
1457
944
    int e = errno;
1458
945
    free(decrypted_buffer);
1459
946
    free(buffer);
1460
947
    if(tcp_sd >= 0){
1461
 
      ret = close(tcp_sd);
 
948
      ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
1462
949
    }
1463
950
    if(ret == -1){
1464
951
      if(e == 0){
1476
963
  return retval;
1477
964
}
1478
965
 
1479
 
__attribute__((nonnull))
1480
966
static void resolve_callback(AvahiSServiceResolver *r,
1481
967
                             AvahiIfIndex interface,
1482
968
                             AvahiProtocol proto,
1490
976
                             AVAHI_GCC_UNUSED AvahiStringList *txt,
1491
977
                             AVAHI_GCC_UNUSED AvahiLookupResultFlags
1492
978
                             flags,
1493
 
                             void *mc){
1494
 
  if(r == NULL){
1495
 
    return;
1496
 
  }
 
979
                             AVAHI_GCC_UNUSED void* userdata){
 
980
  assert(r);
1497
981
  
1498
982
  /* Called whenever a service has been resolved successfully or
1499
983
     timed out */
1500
984
  
1501
985
  if(quit_now){
1502
 
    avahi_s_service_resolver_free(r);
1503
986
    return;
1504
987
  }
1505
988
  
1506
989
  switch(event){
1507
990
  default:
1508
991
  case AVAHI_RESOLVER_FAILURE:
1509
 
    fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service "
1510
 
                 "'%s' of type '%s' in domain '%s': %s\n", name, type,
1511
 
                 domain,
1512
 
                 avahi_strerror(avahi_server_errno
1513
 
                                (((mandos_context*)mc)->server)));
 
992
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
 
993
            " of type '%s' in domain '%s': %s\n", name, type, domain,
 
994
            avahi_strerror(avahi_server_errno(mc.server)));
1514
995
    break;
1515
996
    
1516
997
  case AVAHI_RESOLVER_FOUND:
1518
999
      char ip[AVAHI_ADDRESS_STR_MAX];
1519
1000
      avahi_address_snprint(ip, sizeof(ip), address);
1520
1001
      if(debug){
1521
 
        fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %"
1522
 
                     PRIdMAX ") on port %" PRIu16 "\n", name,
1523
 
                     host_name, ip, (intmax_t)interface, port);
 
1002
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
 
1003
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
 
1004
                ip, (intmax_t)interface, port);
1524
1005
      }
1525
 
      int ret = start_mandos_communication(ip, (in_port_t)port,
1526
 
                                           interface,
1527
 
                                           avahi_proto_to_af(proto),
1528
 
                                           mc);
 
1006
      int ret = start_mandos_communication(ip, port, interface,
 
1007
                                           avahi_proto_to_af(proto));
1529
1008
      if(ret == 0){
1530
 
        avahi_simple_poll_quit(simple_poll);
 
1009
        avahi_simple_poll_quit(mc.simple_poll);
1531
1010
      } else {
1532
 
        if(not add_server(ip, (in_port_t)port, interface,
1533
 
                          avahi_proto_to_af(proto),
1534
 
                          &((mandos_context*)mc)->current_server)){
1535
 
          fprintf_plus(stderr, "Failed to add server \"%s\" to server"
1536
 
                       " list\n", name);
1537
 
        }
 
1011
        ret = add_server(ip, port, interface,
 
1012
                         avahi_proto_to_af(proto));
1538
1013
      }
1539
1014
    }
1540
1015
  }
1550
1025
                            const char *domain,
1551
1026
                            AVAHI_GCC_UNUSED AvahiLookupResultFlags
1552
1027
                            flags,
1553
 
                            void *mc){
1554
 
  if(b == NULL){
1555
 
    return;
1556
 
  }
 
1028
                            AVAHI_GCC_UNUSED void* userdata){
 
1029
  assert(b);
1557
1030
  
1558
1031
  /* Called whenever a new services becomes available on the LAN or
1559
1032
     is removed from the LAN */
1566
1039
  default:
1567
1040
  case AVAHI_BROWSER_FAILURE:
1568
1041
    
1569
 
    fprintf_plus(stderr, "(Avahi browser) %s\n",
1570
 
                 avahi_strerror(avahi_server_errno
1571
 
                                (((mandos_context*)mc)->server)));
1572
 
    avahi_simple_poll_quit(simple_poll);
 
1042
    fprintf(stderr, "(Avahi browser) %s\n",
 
1043
            avahi_strerror(avahi_server_errno(mc.server)));
 
1044
    avahi_simple_poll_quit(mc.simple_poll);
1573
1045
    return;
1574
1046
    
1575
1047
  case AVAHI_BROWSER_NEW:
1578
1050
       the callback function is called the Avahi server will free the
1579
1051
       resolver for us. */
1580
1052
    
1581
 
    if(avahi_s_service_resolver_new(((mandos_context*)mc)->server,
1582
 
                                    interface, protocol, name, type,
1583
 
                                    domain, protocol, 0,
1584
 
                                    resolve_callback, mc) == NULL)
1585
 
      fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':"
1586
 
                   " %s\n", name,
1587
 
                   avahi_strerror(avahi_server_errno
1588
 
                                  (((mandos_context*)mc)->server)));
 
1053
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
 
1054
                                    name, type, domain, protocol, 0,
 
1055
                                    resolve_callback, NULL) == NULL)
 
1056
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
 
1057
              name, avahi_strerror(avahi_server_errno(mc.server)));
1589
1058
    break;
1590
1059
    
1591
1060
  case AVAHI_BROWSER_REMOVE:
1594
1063
  case AVAHI_BROWSER_ALL_FOR_NOW:
1595
1064
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1596
1065
    if(debug){
1597
 
      fprintf_plus(stderr, "No Mandos server found, still"
1598
 
                   " searching...\n");
 
1066
      fprintf(stderr, "No Mandos server found, still searching...\n");
1599
1067
    }
1600
1068
    break;
1601
1069
  }
1602
1070
}
1603
1071
 
1604
 
/* Signal handler that stops main loop after SIGTERM */
 
1072
/* Signal handler that stops main loop after sigterm has been called */
1605
1073
static void handle_sigterm(int sig){
1606
1074
  if(quit_now){
1607
1075
    return;
1610
1078
  signal_received = sig;
1611
1079
  int old_errno = errno;
1612
1080
  /* set main loop to exit */
1613
 
  if(simple_poll != NULL){
1614
 
    avahi_simple_poll_quit(simple_poll);
 
1081
  if(mc.simple_poll != NULL){
 
1082
    avahi_simple_poll_quit(mc.simple_poll);
1615
1083
  }
1616
1084
  errno = old_errno;
1617
1085
}
1618
1086
 
1619
 
__attribute__((nonnull, warn_unused_result))
1620
 
bool get_flags(const char *ifname, struct ifreq *ifr){
1621
 
  int ret;
1622
 
  error_t ret_errno;
1623
 
  
1624
 
  int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1625
 
  if(s < 0){
1626
 
    ret_errno = errno;
1627
 
    perror_plus("socket");
1628
 
    errno = ret_errno;
1629
 
    return false;
1630
 
  }
1631
 
  strncpy(ifr->ifr_name, ifname, IF_NAMESIZE);
1632
 
  ifr->ifr_name[IF_NAMESIZE-1] = '\0'; /* NUL terminate */
1633
 
  ret = ioctl(s, SIOCGIFFLAGS, ifr);
1634
 
  if(ret == -1){
 
1087
/* 
 
1088
 * This function determines if a directory entry in /sys/class/net
 
1089
 * corresponds to an acceptable network device.
 
1090
 * (This function is passed to scandir(3) as a filter function.)
 
1091
 */
 
1092
int good_interface(const struct dirent *if_entry){
 
1093
  ssize_t ssret;
 
1094
  char *flagname = NULL;
 
1095
  if(if_entry->d_name[0] == '.'){
 
1096
    return 0;
 
1097
  }
 
1098
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
 
1099
                     if_entry->d_name);
 
1100
  if(ret < 0){
 
1101
    perror_plus("asprintf");
 
1102
    return 0;
 
1103
  }
 
1104
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
 
1105
  if(flags_fd == -1){
 
1106
    perror_plus("open");
 
1107
    free(flagname);
 
1108
    return 0;
 
1109
  }
 
1110
  free(flagname);
 
1111
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
 
1112
  /* read line from flags_fd */
 
1113
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
 
1114
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
 
1115
  flagstring[(size_t)to_read] = '\0';
 
1116
  if(flagstring == NULL){
 
1117
    perror_plus("malloc");
 
1118
    close(flags_fd);
 
1119
    return 0;
 
1120
  }
 
1121
  while(to_read > 0){
 
1122
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
 
1123
                                             (size_t)to_read));
 
1124
    if(ssret == -1){
 
1125
      perror_plus("read");
 
1126
      free(flagstring);
 
1127
      close(flags_fd);
 
1128
      return 0;
 
1129
    }
 
1130
    to_read -= ssret;
 
1131
    if(ssret == 0){
 
1132
      break;
 
1133
    }
 
1134
  }
 
1135
  close(flags_fd);
 
1136
  intmax_t tmpmax;
 
1137
  char *tmp;
 
1138
  errno = 0;
 
1139
  tmpmax = strtoimax(flagstring, &tmp, 0);
 
1140
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
 
1141
                                         and not (isspace(*tmp)))
 
1142
     or tmpmax != (ifreq_flags)tmpmax){
1635
1143
    if(debug){
1636
 
      ret_errno = errno;
1637
 
      perror_plus("ioctl SIOCGIFFLAGS");
1638
 
      errno = ret_errno;
 
1144
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
 
1145
              flagstring, if_entry->d_name);
1639
1146
    }
1640
 
    return false;
 
1147
    free(flagstring);
 
1148
    return 0;
1641
1149
  }
1642
 
  return true;
1643
 
}
1644
 
 
1645
 
__attribute__((nonnull, warn_unused_result))
1646
 
bool good_flags(const char *ifname, const struct ifreq *ifr){
1647
 
  
 
1150
  free(flagstring);
 
1151
  ifreq_flags flags = (ifreq_flags)tmpmax;
1648
1152
  /* Reject the loopback device */
1649
 
  if(ifr->ifr_flags & IFF_LOOPBACK){
 
1153
  if(flags & IFF_LOOPBACK){
1650
1154
    if(debug){
1651
 
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
1652
 
                   ifname);
 
1155
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
 
1156
              if_entry->d_name);
1653
1157
    }
1654
 
    return false;
 
1158
    return 0;
1655
1159
  }
1656
1160
  /* Accept point-to-point devices only if connect_to is specified */
1657
 
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
 
1161
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
1658
1162
    if(debug){
1659
 
      fprintf_plus(stderr, "Accepting point-to-point interface"
1660
 
                   " \"%s\"\n", ifname);
 
1163
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
 
1164
              if_entry->d_name);
1661
1165
    }
1662
 
    return true;
 
1166
    return 1;
1663
1167
  }
1664
1168
  /* Otherwise, reject non-broadcast-capable devices */
1665
 
  if(not (ifr->ifr_flags & IFF_BROADCAST)){
 
1169
  if(not (flags & IFF_BROADCAST)){
1666
1170
    if(debug){
1667
 
      fprintf_plus(stderr, "Rejecting non-broadcast interface"
1668
 
                   " \"%s\"\n", ifname);
 
1171
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
 
1172
              if_entry->d_name);
1669
1173
    }
1670
 
    return false;
 
1174
    return 0;
1671
1175
  }
1672
1176
  /* Reject non-ARP interfaces (including dummy interfaces) */
1673
 
  if(ifr->ifr_flags & IFF_NOARP){
 
1177
  if(flags & IFF_NOARP){
1674
1178
    if(debug){
1675
 
      fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n",
1676
 
                   ifname);
 
1179
      fprintf(stderr, "Rejecting non-ARP interface \"%s\"\n",
 
1180
              if_entry->d_name);
1677
1181
    }
1678
 
    return false;
 
1182
    return 0;
1679
1183
  }
1680
 
  
1681
1184
  /* Accept this device */
1682
1185
  if(debug){
1683
 
    fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname);
1684
 
  }
1685
 
  return true;
1686
 
}
1687
 
 
1688
 
/* 
1689
 
 * This function determines if a directory entry in /sys/class/net
1690
 
 * corresponds to an acceptable network device.
1691
 
 * (This function is passed to scandir(3) as a filter function.)
1692
 
 */
1693
 
__attribute__((nonnull, warn_unused_result))
1694
 
int good_interface(const struct dirent *if_entry){
1695
 
  if(if_entry->d_name[0] == '.'){
1696
 
    return 0;
1697
 
  }
1698
 
  
1699
 
  struct ifreq ifr;
1700
 
  if(not get_flags(if_entry->d_name, &ifr)){
1701
 
    if(debug){
1702
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1703
 
                   "\"%s\"\n", if_entry->d_name);
1704
 
    }
1705
 
    return 0;
1706
 
  }
1707
 
  
1708
 
  if(not good_flags(if_entry->d_name, &ifr)){
1709
 
    return 0;
 
1186
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
 
1187
            if_entry->d_name);
1710
1188
  }
1711
1189
  return 1;
1712
1190
}
1713
1191
 
1714
 
/* 
1715
 
 * This function determines if a network interface is up.
1716
 
 */
1717
 
__attribute__((nonnull, warn_unused_result))
1718
 
bool interface_is_up(const char *interface){
1719
 
  struct ifreq ifr;
1720
 
  if(not get_flags(interface, &ifr)){
1721
 
    if(debug){
1722
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1723
 
                   "\"%s\"\n", interface);
1724
 
    }
1725
 
    return false;
1726
 
  }
1727
 
  
1728
 
  return (bool)(ifr.ifr_flags & IFF_UP);
1729
 
}
1730
 
 
1731
 
/* 
1732
 
 * This function determines if a network interface is running
1733
 
 */
1734
 
__attribute__((nonnull, warn_unused_result))
1735
 
bool interface_is_running(const char *interface){
1736
 
  struct ifreq ifr;
1737
 
  if(not get_flags(interface, &ifr)){
1738
 
    if(debug){
1739
 
      fprintf_plus(stderr, "Failed to get flags for interface "
1740
 
                   "\"%s\"\n", interface);
1741
 
    }
1742
 
    return false;
1743
 
  }
1744
 
  
1745
 
  return (bool)(ifr.ifr_flags & IFF_RUNNING);
1746
 
}
1747
 
 
1748
 
__attribute__((nonnull, pure, warn_unused_result))
1749
1192
int notdotentries(const struct dirent *direntry){
1750
1193
  /* Skip "." and ".." */
1751
1194
  if(direntry->d_name[0] == '.'
1757
1200
  return 1;
1758
1201
}
1759
1202
 
1760
 
/* Is this directory entry a runnable program? */
1761
 
__attribute__((nonnull, warn_unused_result))
1762
 
int runnable_hook(const struct dirent *direntry){
1763
 
  int ret;
1764
 
  size_t sret;
1765
 
  struct stat st;
1766
 
  
1767
 
  if((direntry->d_name)[0] == '\0'){
1768
 
    /* Empty name? */
1769
 
    return 0;
1770
 
  }
1771
 
  
1772
 
  sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1773
 
                "abcdefghijklmnopqrstuvwxyz"
1774
 
                "0123456789"
1775
 
                "_.-");
1776
 
  if((direntry->d_name)[sret] != '\0'){
1777
 
    /* Contains non-allowed characters */
1778
 
    if(debug){
1779
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n",
1780
 
                   direntry->d_name);
1781
 
    }
1782
 
    return 0;
1783
 
  }
1784
 
  
1785
 
  ret = fstatat(hookdir_fd, direntry->d_name, &st, 0);
1786
 
  if(ret == -1){
1787
 
    if(debug){
1788
 
      perror_plus("Could not stat hook");
1789
 
    }
1790
 
    return 0;
1791
 
  }
1792
 
  if(not (S_ISREG(st.st_mode))){
1793
 
    /* Not a regular file */
1794
 
    if(debug){
1795
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n",
1796
 
                   direntry->d_name);
1797
 
    }
1798
 
    return 0;
1799
 
  }
1800
 
  if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){
1801
 
    /* Not executable */
1802
 
    if(debug){
1803
 
      fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n",
1804
 
                   direntry->d_name);
1805
 
    }
1806
 
    return 0;
1807
 
  }
1808
 
  if(debug){
1809
 
    fprintf_plus(stderr, "Hook \"%s\" is acceptable\n",
1810
 
                 direntry->d_name);
1811
 
  }
1812
 
  return 1;
1813
 
}
1814
 
 
1815
 
__attribute__((nonnull, warn_unused_result))
1816
 
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval,
1817
 
                            mandos_context *mc){
 
1203
int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval){
1818
1204
  int ret;
1819
1205
  struct timespec now;
1820
1206
  struct timespec waited_time;
1821
1207
  intmax_t block_time;
1822
 
  
 
1208
 
1823
1209
  while(true){
1824
 
    if(mc->current_server == NULL){
1825
 
      if(debug){
1826
 
        fprintf_plus(stderr, "Wait until first server is found."
1827
 
                     " No timeout!\n");
 
1210
    if(mc.current_server == NULL){
 
1211
      if (debug){
 
1212
        fprintf(stderr, "Wait until first server is found. No timeout!\n");     
1828
1213
      }
1829
1214
      ret = avahi_simple_poll_iterate(s, -1);
1830
1215
    } else {
1831
 
      if(debug){
1832
 
        fprintf_plus(stderr, "Check current_server if we should run"
1833
 
                     " it, or wait\n");
 
1216
      if (debug){
 
1217
        fprintf(stderr, "Check current_server if we should run it, or wait\n"); 
1834
1218
      }
1835
1219
      /* the current time */
1836
1220
      ret = clock_gettime(CLOCK_MONOTONIC, &now);
1840
1224
      }
1841
1225
      /* Calculating in ms how long time between now and server
1842
1226
         who we visted longest time ago. Now - last seen.  */
1843
 
      waited_time.tv_sec = (now.tv_sec
1844
 
                            - mc->current_server->last_seen.tv_sec);
1845
 
      waited_time.tv_nsec = (now.tv_nsec
1846
 
                             - mc->current_server->last_seen.tv_nsec);
1847
 
      /* total time is 10s/10,000ms.
1848
 
         Converting to s from ms by dividing by 1,000,
1849
 
         and ns to ms by dividing by 1,000,000. */
1850
 
      block_time = ((retry_interval
1851
 
                     - ((intmax_t)waited_time.tv_sec * 1000))
1852
 
                    - ((intmax_t)waited_time.tv_nsec / 1000000));
1853
 
      
1854
 
      if(debug){
1855
 
        fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n",
1856
 
                     block_time);
 
1227
      waited_time.tv_sec = now.tv_sec - mc.current_server->last_seen.tv_sec;
 
1228
      waited_time.tv_nsec = now.tv_nsec - mc.current_server->last_seen.tv_nsec;
 
1229
      /* total time is 10s/10000ms. Converting to s to ms by 1000/s, and ns to ms by divind by 1000000. */
 
1230
      block_time = (retry_interval - ((intmax_t)waited_time.tv_sec * 1000)) - ((intmax_t)waited_time.tv_nsec / 1000000);
 
1231
 
 
1232
      if (debug){
 
1233
        fprintf(stderr, "Blocking for %ld ms\n", block_time);   
1857
1234
      }
1858
 
      
 
1235
 
1859
1236
      if(block_time <= 0){
1860
 
        ret = start_mandos_communication(mc->current_server->ip,
1861
 
                                         mc->current_server->port,
1862
 
                                         mc->current_server->if_index,
1863
 
                                         mc->current_server->af, mc);
 
1237
        ret = start_mandos_communication(mc.current_server->ip,
 
1238
                                   mc.current_server->port,
 
1239
                                   mc.current_server->if_index,
 
1240
                                   mc.current_server->af);
1864
1241
        if(ret == 0){
1865
 
          avahi_simple_poll_quit(s);
 
1242
          avahi_simple_poll_quit(mc.simple_poll);
1866
1243
          return 0;
1867
1244
        }
1868
 
        ret = clock_gettime(CLOCK_MONOTONIC,
1869
 
                            &mc->current_server->last_seen);
 
1245
        ret = clock_gettime(CLOCK_MONOTONIC, &mc.current_server->last_seen);
1870
1246
        if(ret == -1){
1871
1247
          perror_plus("clock_gettime");
1872
1248
          return -1;
1873
1249
        }
1874
 
        mc->current_server = mc->current_server->next;
1875
 
        block_time = 0;         /* Call avahi to find new Mandos
1876
 
                                   servers, but don't block */
 
1250
        mc.current_server = mc.current_server->next;
 
1251
        block_time = 0;         /* call avahi to find new mandos servers, but dont block */
1877
1252
      }
1878
1253
      
1879
1254
      ret = avahi_simple_poll_iterate(s, (int)block_time);
1880
1255
    }
1881
1256
    if(ret != 0){
1882
 
      if(ret > 0 or errno != EINTR){
 
1257
      if (ret > 0 or errno != EINTR) {
1883
1258
        return (ret != 1) ? ret : 0;
1884
1259
      }
1885
1260
    }
1886
1261
  }
1887
1262
}
1888
1263
 
1889
 
__attribute__((nonnull))
1890
 
void run_network_hooks(const char *mode, const char *interface,
1891
 
                       const float delay){
1892
 
  struct dirent **direntries = NULL;
1893
 
  if(hookdir_fd == -1){
1894
 
    hookdir_fd = open(hookdir, O_RDONLY | O_DIRECTORY | O_PATH
1895
 
                      | O_CLOEXEC);
1896
 
    if(hookdir_fd == -1){
1897
 
      if(errno == ENOENT){
1898
 
        if(debug){
1899
 
          fprintf_plus(stderr, "Network hook directory \"%s\" not"
1900
 
                       " found\n", hookdir);
1901
 
        }
1902
 
      } else {
1903
 
        perror_plus("open");
1904
 
      }
1905
 
      return;
1906
 
    }
1907
 
  }
1908
 
  int numhooks = scandirat(hookdir_fd, ".", &direntries,
1909
 
                           runnable_hook, alphasort);
1910
 
  if(numhooks == -1){
1911
 
    perror_plus("scandir");
1912
 
    return;
1913
 
  }
1914
 
  struct dirent *direntry;
1915
 
  int ret;
1916
 
  int devnull = (int)TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
1917
 
  if(devnull == -1){
1918
 
    perror_plus("open(\"/dev/null\", O_RDONLY)");
1919
 
    return;
1920
 
  }
1921
 
  for(int i = 0; i < numhooks; i++){
1922
 
    direntry = direntries[i];
1923
 
    if(debug){
1924
 
      fprintf_plus(stderr, "Running network hook \"%s\"\n",
1925
 
                   direntry->d_name);
1926
 
    }
1927
 
    pid_t hook_pid = fork();
1928
 
    if(hook_pid == 0){
1929
 
      /* Child */
1930
 
      /* Raise privileges */
1931
 
      errno = raise_privileges_permanently();
1932
 
      if(errno != 0){
1933
 
        perror_plus("Failed to raise privileges");
1934
 
        _exit(EX_NOPERM);
1935
 
      }
1936
 
      /* Set group */
1937
 
      errno = 0;
1938
 
      ret = setgid(0);
1939
 
      if(ret == -1){
1940
 
        perror_plus("setgid");
1941
 
        _exit(EX_NOPERM);
1942
 
      }
1943
 
      /* Reset supplementary groups */
1944
 
      errno = 0;
1945
 
      ret = setgroups(0, NULL);
1946
 
      if(ret == -1){
1947
 
        perror_plus("setgroups");
1948
 
        _exit(EX_NOPERM);
1949
 
      }
1950
 
      ret = setenv("MANDOSNETHOOKDIR", hookdir, 1);
1951
 
      if(ret == -1){
1952
 
        perror_plus("setenv");
1953
 
        _exit(EX_OSERR);
1954
 
      }
1955
 
      ret = setenv("DEVICE", interface, 1);
1956
 
      if(ret == -1){
1957
 
        perror_plus("setenv");
1958
 
        _exit(EX_OSERR);
1959
 
      }
1960
 
      ret = setenv("VERBOSITY", debug ? "1" : "0", 1);
1961
 
      if(ret == -1){
1962
 
        perror_plus("setenv");
1963
 
        _exit(EX_OSERR);
1964
 
      }
1965
 
      ret = setenv("MODE", mode, 1);
1966
 
      if(ret == -1){
1967
 
        perror_plus("setenv");
1968
 
        _exit(EX_OSERR);
1969
 
      }
1970
 
      char *delaystring;
1971
 
      ret = asprintf(&delaystring, "%f", (double)delay);
1972
 
      if(ret == -1){
1973
 
        perror_plus("asprintf");
1974
 
        _exit(EX_OSERR);
1975
 
      }
1976
 
      ret = setenv("DELAY", delaystring, 1);
1977
 
      if(ret == -1){
1978
 
        free(delaystring);
1979
 
        perror_plus("setenv");
1980
 
        _exit(EX_OSERR);
1981
 
      }
1982
 
      free(delaystring);
1983
 
      if(connect_to != NULL){
1984
 
        ret = setenv("CONNECT", connect_to, 1);
1985
 
        if(ret == -1){
1986
 
          perror_plus("setenv");
1987
 
          _exit(EX_OSERR);
1988
 
        }
1989
 
      }
1990
 
      int hook_fd = (int)TEMP_FAILURE_RETRY(openat(hookdir_fd,
1991
 
                                                   direntry->d_name,
1992
 
                                                   O_RDONLY));
1993
 
      if(hook_fd == -1){
1994
 
        perror_plus("openat");
1995
 
        _exit(EXIT_FAILURE);
1996
 
      }
1997
 
      if(close(hookdir_fd) == -1){
1998
 
        perror_plus("close");
1999
 
        _exit(EXIT_FAILURE);
2000
 
      }
2001
 
      ret = dup2(devnull, STDIN_FILENO);
2002
 
      if(ret == -1){
2003
 
        perror_plus("dup2(devnull, STDIN_FILENO)");
2004
 
        _exit(EX_OSERR);
2005
 
      }
2006
 
      ret = close(devnull);
2007
 
      if(ret == -1){
2008
 
        perror_plus("close");
2009
 
        _exit(EX_OSERR);
2010
 
      }
2011
 
      ret = dup2(STDERR_FILENO, STDOUT_FILENO);
2012
 
      if(ret == -1){
2013
 
        perror_plus("dup2(STDERR_FILENO, STDOUT_FILENO)");
2014
 
        _exit(EX_OSERR);
2015
 
      }
2016
 
      if(fexecve(hook_fd, (char *const []){ direntry->d_name, NULL },
2017
 
                 environ) == -1){
2018
 
        perror_plus("fexecve");
2019
 
        _exit(EXIT_FAILURE);
2020
 
      }
2021
 
    } else {
2022
 
      if(hook_pid == -1){
2023
 
        perror_plus("fork");
2024
 
        free(direntry);
2025
 
        continue;
2026
 
      }
2027
 
      int status;
2028
 
      if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){
2029
 
        perror_plus("waitpid");
2030
 
        free(direntry);
2031
 
        continue;
2032
 
      }
2033
 
      if(WIFEXITED(status)){
2034
 
        if(WEXITSTATUS(status) != 0){
2035
 
          fprintf_plus(stderr, "Warning: network hook \"%s\" exited"
2036
 
                       " with status %d\n", direntry->d_name,
2037
 
                       WEXITSTATUS(status));
2038
 
          free(direntry);
2039
 
          continue;
2040
 
        }
2041
 
      } else if(WIFSIGNALED(status)){
2042
 
        fprintf_plus(stderr, "Warning: network hook \"%s\" died by"
2043
 
                     " signal %d\n", direntry->d_name,
2044
 
                     WTERMSIG(status));
2045
 
        free(direntry);
2046
 
        continue;
2047
 
      } else {
2048
 
        fprintf_plus(stderr, "Warning: network hook \"%s\""
2049
 
                     " crashed\n", direntry->d_name);
2050
 
        free(direntry);
2051
 
        continue;
2052
 
      }
2053
 
    }
2054
 
    if(debug){
2055
 
      fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n",
2056
 
                   direntry->d_name);
2057
 
    }
2058
 
    free(direntry);
2059
 
  }
2060
 
  free(direntries);
2061
 
  if(close(hookdir_fd) == -1){
2062
 
    perror_plus("close");
2063
 
  } else {
2064
 
    hookdir_fd = -1;
2065
 
  }
2066
 
  close(devnull);
2067
 
}
2068
 
 
2069
 
__attribute__((nonnull, warn_unused_result))
2070
 
error_t bring_up_interface(const char *const interface,
2071
 
                           const float delay){
2072
 
  error_t old_errno = errno;
2073
 
  int ret;
2074
 
  struct ifreq network;
2075
 
  unsigned int if_index = if_nametoindex(interface);
2076
 
  if(if_index == 0){
2077
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2078
 
    errno = old_errno;
2079
 
    return ENXIO;
2080
 
  }
2081
 
  
2082
 
  if(quit_now){
2083
 
    errno = old_errno;
2084
 
    return EINTR;
2085
 
  }
2086
 
  
2087
 
  if(not interface_is_up(interface)){
2088
 
    error_t ret_errno = 0, ioctl_errno = 0;
2089
 
    if(not get_flags(interface, &network)){
2090
 
      ret_errno = errno;
2091
 
      fprintf_plus(stderr, "Failed to get flags for interface "
2092
 
                   "\"%s\"\n", interface);
2093
 
      errno = old_errno;
2094
 
      return ret_errno;
2095
 
    }
2096
 
    network.ifr_flags |= IFF_UP; /* set flag */
2097
 
    
2098
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2099
 
    if(sd == -1){
2100
 
      ret_errno = errno;
2101
 
      perror_plus("socket");
2102
 
      errno = old_errno;
2103
 
      return ret_errno;
2104
 
    }
2105
 
    
2106
 
    if(quit_now){
2107
 
      ret = close(sd);
2108
 
      if(ret == -1){
2109
 
        perror_plus("close");
2110
 
      }
2111
 
      errno = old_errno;
2112
 
      return EINTR;
2113
 
    }
2114
 
    
2115
 
    if(debug){
2116
 
      fprintf_plus(stderr, "Bringing up interface \"%s\"\n",
2117
 
                   interface);
2118
 
    }
2119
 
    
2120
 
    /* Raise privileges */
2121
 
    ret_errno = raise_privileges();
2122
 
    if(ret_errno != 0){
2123
 
      errno = ret_errno;
2124
 
      perror_plus("Failed to raise privileges");
2125
 
    }
2126
 
    
2127
 
#ifdef __linux__
2128
 
    int ret_linux;
2129
 
    bool restore_loglevel = false;
2130
 
    if(ret_errno == 0){
2131
 
      /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
2132
 
         messages about the network interface to mess up the prompt */
2133
 
      ret_linux = klogctl(8, NULL, 5);
2134
 
      if(ret_linux == -1){
2135
 
        perror_plus("klogctl");
2136
 
      } else {
2137
 
        restore_loglevel = true;
2138
 
      }
2139
 
    }
2140
 
#endif  /* __linux__ */
2141
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2142
 
    ioctl_errno = errno;
2143
 
#ifdef __linux__
2144
 
    if(restore_loglevel){
2145
 
      ret_linux = klogctl(7, NULL, 0);
2146
 
      if(ret_linux == -1){
2147
 
        perror_plus("klogctl");
2148
 
      }
2149
 
    }
2150
 
#endif  /* __linux__ */
2151
 
    
2152
 
    /* If raise_privileges() succeeded above */
2153
 
    if(ret_errno == 0){
2154
 
      /* Lower privileges */
2155
 
      ret_errno = lower_privileges();
2156
 
      if(ret_errno != 0){
2157
 
        errno = ret_errno;
2158
 
        perror_plus("Failed to lower privileges");
2159
 
      }
2160
 
    }
2161
 
    
2162
 
    /* Close the socket */
2163
 
    ret = close(sd);
2164
 
    if(ret == -1){
2165
 
      perror_plus("close");
2166
 
    }
2167
 
    
2168
 
    if(ret_setflags == -1){
2169
 
      errno = ioctl_errno;
2170
 
      perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
2171
 
      errno = old_errno;
2172
 
      return ioctl_errno;
2173
 
    }
2174
 
  } else if(debug){
2175
 
    fprintf_plus(stderr, "Interface \"%s\" is already up; good\n",
2176
 
                 interface);
2177
 
  }
2178
 
  
2179
 
  /* Sleep checking until interface is running.
2180
 
     Check every 0.25s, up to total time of delay */
2181
 
  for(int i=0; i < delay * 4; i++){
2182
 
    if(interface_is_running(interface)){
2183
 
      break;
2184
 
    }
2185
 
    struct timespec sleeptime = { .tv_nsec = 250000000 };
2186
 
    ret = nanosleep(&sleeptime, NULL);
2187
 
    if(ret == -1 and errno != EINTR){
2188
 
      perror_plus("nanosleep");
2189
 
    }
2190
 
  }
2191
 
  
2192
 
  errno = old_errno;
2193
 
  return 0;
2194
 
}
2195
 
 
2196
 
__attribute__((nonnull, warn_unused_result))
2197
 
error_t take_down_interface(const char *const interface){
2198
 
  error_t old_errno = errno;
2199
 
  struct ifreq network;
2200
 
  unsigned int if_index = if_nametoindex(interface);
2201
 
  if(if_index == 0){
2202
 
    fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
2203
 
    errno = old_errno;
2204
 
    return ENXIO;
2205
 
  }
2206
 
  if(interface_is_up(interface)){
2207
 
    error_t ret_errno = 0, ioctl_errno = 0;
2208
 
    if(not get_flags(interface, &network) and debug){
2209
 
      ret_errno = errno;
2210
 
      fprintf_plus(stderr, "Failed to get flags for interface "
2211
 
                   "\"%s\"\n", interface);
2212
 
      errno = old_errno;
2213
 
      return ret_errno;
2214
 
    }
2215
 
    network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
2216
 
    
2217
 
    int sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
2218
 
    if(sd == -1){
2219
 
      ret_errno = errno;
2220
 
      perror_plus("socket");
2221
 
      errno = old_errno;
2222
 
      return ret_errno;
2223
 
    }
2224
 
    
2225
 
    if(debug){
2226
 
      fprintf_plus(stderr, "Taking down interface \"%s\"\n",
2227
 
                   interface);
2228
 
    }
2229
 
    
2230
 
    /* Raise privileges */
2231
 
    ret_errno = raise_privileges();
2232
 
    if(ret_errno != 0){
2233
 
      errno = ret_errno;
2234
 
      perror_plus("Failed to raise privileges");
2235
 
    }
2236
 
    
2237
 
    int ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network);
2238
 
    ioctl_errno = errno;
2239
 
    
2240
 
    /* If raise_privileges() succeeded above */
2241
 
    if(ret_errno == 0){
2242
 
      /* Lower privileges */
2243
 
      ret_errno = lower_privileges();
2244
 
      if(ret_errno != 0){
2245
 
        errno = ret_errno;
2246
 
        perror_plus("Failed to lower privileges");
2247
 
      }
2248
 
    }
2249
 
    
2250
 
    /* Close the socket */
2251
 
    int ret = close(sd);
2252
 
    if(ret == -1){
2253
 
      perror_plus("close");
2254
 
    }
2255
 
    
2256
 
    if(ret_setflags == -1){
2257
 
      errno = ioctl_errno;
2258
 
      perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
2259
 
      errno = old_errno;
2260
 
      return ioctl_errno;
2261
 
    }
2262
 
  } else if(debug){
2263
 
    fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n",
2264
 
                 interface);
2265
 
  }
2266
 
  
2267
 
  errno = old_errno;
2268
 
  return 0;
2269
 
}
2270
 
 
2271
1264
int main(int argc, char *argv[]){
2272
 
  mandos_context mc = { .server = NULL, .dh_bits = 0,
2273
 
                        .priority = "SECURE256:!CTYPE-X.509"
2274
 
                        ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256",
2275
 
                        .current_server = NULL, .interfaces = NULL,
2276
 
                        .interfaces_size = 0 };
2277
1265
  AvahiSServiceBrowser *sb = NULL;
2278
 
  error_t ret_errno;
 
1266
  int error;
2279
1267
  int ret;
2280
1268
  intmax_t tmpmax;
2281
1269
  char *tmp;
2282
1270
  int exitcode = EXIT_SUCCESS;
2283
 
  char *interfaces_to_take_down = NULL;
2284
 
  size_t interfaces_to_take_down_size = 0;
2285
 
  char run_tempdir[] = "/run/tmp/mandosXXXXXX";
2286
 
  char old_tempdir[] = "/tmp/mandosXXXXXX";
2287
 
  char *tempdir = NULL;
 
1271
  const char *interface = "";
 
1272
  struct ifreq network;
 
1273
  int sd = -1;
 
1274
  bool take_down_interface = false;
 
1275
  uid_t uid;
 
1276
  gid_t gid;
 
1277
  char tempdir[] = "/tmp/mandosXXXXXX";
 
1278
  bool tempdir_created = false;
2288
1279
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
2289
1280
  const char *seckey = PATHDIR "/" SECKEY;
2290
1281
  const char *pubkey = PATHDIR "/" PUBKEY;
2291
 
  const char *dh_params_file = NULL;
2292
 
  char *interfaces_hooks = NULL;
2293
1282
  
2294
1283
  bool gnutls_initialized = false;
2295
1284
  bool gpgme_initialized = false;
2296
1285
  float delay = 2.5f;
2297
 
  double retry_interval = 10; /* 10s between trying a server and
2298
 
                                 retrying the same server again */
 
1286
  double retry_interval = 10; /* 10s between retrying a server and checking again*/
2299
1287
  
2300
1288
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
2301
1289
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
2347
1335
        .doc = "Bit length of the prime number used in the"
2348
1336
        " Diffie-Hellman key exchange",
2349
1337
        .group = 2 },
2350
 
      { .name = "dh-params", .key = 134,
2351
 
        .arg = "FILE",
2352
 
        .doc = "PEM-encoded PKCS#3 file with pre-generated parameters"
2353
 
        " for the Diffie-Hellman key exchange",
2354
 
        .group = 2 },
2355
1338
      { .name = "priority", .key = 130,
2356
1339
        .arg = "STRING",
2357
1340
        .doc = "GnuTLS priority string for the TLS handshake",
2362
1345
        .group = 2 },
2363
1346
      { .name = "retry", .key = 132,
2364
1347
        .arg = "SECONDS",
2365
 
        .doc = "Retry interval used when denied by the Mandos server",
2366
 
        .group = 2 },
2367
 
      { .name = "network-hook-dir", .key = 133,
2368
 
        .arg = "DIR",
2369
 
        .doc = "Directory where network hooks are located",
 
1348
        .doc = "Retry interval used when denied by the mandos server",
2370
1349
        .group = 2 },
2371
1350
      /*
2372
1351
       * These reproduce what we would get without ARGP_NO_HELP
2391
1370
        connect_to = arg;
2392
1371
        break;
2393
1372
      case 'i':                 /* --interface */
2394
 
        ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size,
2395
 
                                 arg, (int)',');
2396
 
        if(ret_errno != 0){
2397
 
          argp_error(state, "%s", strerror(ret_errno));
2398
 
        }
 
1373
        interface = arg;
2399
1374
        break;
2400
1375
      case 's':                 /* --seckey */
2401
1376
        seckey = arg;
2412
1387
        }
2413
1388
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
2414
1389
        break;
2415
 
      case 134:                 /* --dh-params */
2416
 
        dh_params_file = arg;
2417
 
        break;
2418
1390
      case 130:                 /* --priority */
2419
1391
        mc.priority = arg;
2420
1392
        break;
2428
1400
        errno = 0;
2429
1401
        retry_interval = strtod(arg, &tmp);
2430
1402
        if(errno != 0 or tmp == arg or *tmp != '\0'
2431
 
           or (retry_interval * 1000) > INT_MAX
2432
 
           or retry_interval < 0){
 
1403
           or (retry_interval * 1000) > INT_MAX){
2433
1404
          argp_error(state, "Bad retry interval");
2434
1405
        }
2435
1406
        break;
2436
 
      case 133:                 /* --network-hook-dir */
2437
 
        hookdir = arg;
2438
 
        break;
2439
1407
        /*
2440
1408
         * These reproduce what we would get without ARGP_NO_HELP
2441
1409
         */
2447
1415
        argp_state_help(state, state->out_stream,
2448
1416
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
2449
1417
      case 'V':                 /* --version */
2450
 
        fprintf_plus(state->out_stream, "%s\n", argp_program_version);
 
1418
        fprintf(state->out_stream, "%s\n", argp_program_version);
2451
1419
        exit(argp_err_exit_status);
2452
1420
        break;
2453
1421
      default:
2477
1445
    }
2478
1446
  }
2479
1447
  
2480
 
  {
2481
 
    /* Work around Debian bug #633582:
2482
 
       <http://bugs.debian.org/633582> */
2483
 
    
2484
 
    /* Re-raise privileges */
2485
 
    ret_errno = raise_privileges();
2486
 
    if(ret_errno != 0){
2487
 
      errno = ret_errno;
2488
 
      perror_plus("Failed to raise privileges");
2489
 
    } else {
2490
 
      struct stat st;
2491
 
      
2492
 
      if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){
2493
 
        int seckey_fd = open(seckey, O_RDONLY);
2494
 
        if(seckey_fd == -1){
2495
 
          perror_plus("open");
2496
 
        } else {
2497
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st));
2498
 
          if(ret == -1){
2499
 
            perror_plus("fstat");
2500
 
          } else {
2501
 
            if(S_ISREG(st.st_mode)
2502
 
               and st.st_uid == 0 and st.st_gid == 0){
2503
 
              ret = fchown(seckey_fd, uid, gid);
2504
 
              if(ret == -1){
2505
 
                perror_plus("fchown");
2506
 
              }
2507
 
            }
2508
 
          }
2509
 
          close(seckey_fd);
2510
 
        }
2511
 
      }
2512
 
      
2513
 
      if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){
2514
 
        int pubkey_fd = open(pubkey, O_RDONLY);
2515
 
        if(pubkey_fd == -1){
2516
 
          perror_plus("open");
2517
 
        } else {
2518
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st));
2519
 
          if(ret == -1){
2520
 
            perror_plus("fstat");
2521
 
          } else {
2522
 
            if(S_ISREG(st.st_mode)
2523
 
               and st.st_uid == 0 and st.st_gid == 0){
2524
 
              ret = fchown(pubkey_fd, uid, gid);
2525
 
              if(ret == -1){
2526
 
                perror_plus("fchown");
2527
 
              }
2528
 
            }
2529
 
          }
2530
 
          close(pubkey_fd);
2531
 
        }
2532
 
      }
2533
 
      
2534
 
      if(dh_params_file != NULL
2535
 
         and strcmp(dh_params_file, PATHDIR "/dhparams.pem" ) == 0){
2536
 
        int dhparams_fd = open(dh_params_file, O_RDONLY);
2537
 
        if(dhparams_fd == -1){
2538
 
          perror_plus("open");
2539
 
        } else {
2540
 
          ret = (int)TEMP_FAILURE_RETRY(fstat(dhparams_fd, &st));
2541
 
          if(ret == -1){
2542
 
            perror_plus("fstat");
2543
 
          } else {
2544
 
            if(S_ISREG(st.st_mode)
2545
 
               and st.st_uid == 0 and st.st_gid == 0){
2546
 
              ret = fchown(dhparams_fd, uid, gid);
2547
 
              if(ret == -1){
2548
 
                perror_plus("fchown");
2549
 
              }
2550
 
            }
2551
 
          }
2552
 
          close(dhparams_fd);
2553
 
        }
2554
 
      }
2555
 
      
2556
 
      /* Lower privileges */
2557
 
      ret_errno = lower_privileges();
2558
 
      if(ret_errno != 0){
2559
 
        errno = ret_errno;
2560
 
        perror_plus("Failed to lower privileges");
2561
 
      }
2562
 
    }
2563
 
  }
2564
 
  
2565
 
  /* Remove invalid interface names (except "none") */
2566
 
  {
2567
 
    char *interface = NULL;
2568
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2569
 
                                 interface))){
2570
 
      if(strcmp(interface, "none") != 0
2571
 
         and if_nametoindex(interface) == 0){
2572
 
        if(interface[0] != '\0'){
2573
 
          fprintf_plus(stderr, "Not using nonexisting interface"
2574
 
                       " \"%s\"\n", interface);
2575
 
        }
2576
 
        argz_delete(&mc.interfaces, &mc.interfaces_size, interface);
2577
 
        interface = NULL;
2578
 
      }
2579
 
    }
2580
 
  }
2581
 
  
2582
 
  /* Run network hooks */
2583
 
  {
2584
 
    if(mc.interfaces != NULL){
2585
 
      interfaces_hooks = malloc(mc.interfaces_size);
2586
 
      if(interfaces_hooks == NULL){
2587
 
        perror_plus("malloc");
2588
 
        goto end;
2589
 
      }
2590
 
      memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size);
2591
 
      argz_stringify(interfaces_hooks, mc.interfaces_size, (int)',');
2592
 
    }
2593
 
    run_network_hooks("start", interfaces_hooks != NULL ?
2594
 
                      interfaces_hooks : "", delay);
2595
 
  }
2596
 
  
2597
1448
  if(not debug){
2598
1449
    avahi_set_log_function(empty_log);
2599
1450
  }
 
1451
 
 
1452
  if(interface[0] == '\0'){
 
1453
    struct dirent **direntries;
 
1454
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1455
                  alphasort);
 
1456
    if(ret >= 1){
 
1457
      /* Pick the first good interface */
 
1458
      interface = strdup(direntries[0]->d_name);
 
1459
      if(debug){
 
1460
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1461
      }
 
1462
      if(interface == NULL){
 
1463
        perror_plus("malloc");
 
1464
        free(direntries);
 
1465
        exitcode = EXIT_FAILURE;
 
1466
        goto end;
 
1467
      }
 
1468
      free(direntries);
 
1469
    } else {
 
1470
      free(direntries);
 
1471
      fprintf(stderr, "Could not find a network interface\n");
 
1472
      exitcode = EXIT_FAILURE;
 
1473
      goto end;
 
1474
    }
 
1475
  }
2600
1476
  
2601
1477
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
2602
1478
     from the signal handler */
2603
1479
  /* Initialize the pseudo-RNG for Avahi */
2604
1480
  srand((unsigned int) time(NULL));
2605
 
  simple_poll = avahi_simple_poll_new();
2606
 
  if(simple_poll == NULL){
2607
 
    fprintf_plus(stderr,
2608
 
                 "Avahi: Failed to create simple poll object.\n");
 
1481
  mc.simple_poll = avahi_simple_poll_new();
 
1482
  if(mc.simple_poll == NULL){
 
1483
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
2609
1484
    exitcode = EX_UNAVAILABLE;
2610
1485
    goto end;
2611
1486
  }
2673
1548
    }
2674
1549
  }
2675
1550
  
2676
 
  /* If no interfaces were specified, make a list */
2677
 
  if(mc.interfaces == NULL){
2678
 
    struct dirent **direntries = NULL;
2679
 
    /* Look for any good interfaces */
2680
 
    ret = scandir(sys_class_net, &direntries, good_interface,
2681
 
                  alphasort);
2682
 
    if(ret >= 1){
2683
 
      /* Add all found interfaces to interfaces list */
2684
 
      for(int i = 0; i < ret; ++i){
2685
 
        ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size,
2686
 
                             direntries[i]->d_name);
2687
 
        if(ret_errno != 0){
2688
 
          errno = ret_errno;
2689
 
          perror_plus("argz_add");
2690
 
          free(direntries[i]);
2691
 
          continue;
2692
 
        }
2693
 
        if(debug){
2694
 
          fprintf_plus(stderr, "Will use interface \"%s\"\n",
2695
 
                       direntries[i]->d_name);
2696
 
        }
2697
 
        free(direntries[i]);
2698
 
      }
2699
 
      free(direntries);
 
1551
  /* If the interface is down, bring it up */
 
1552
  if(strcmp(interface, "none") != 0){
 
1553
    if_index = (AvahiIfIndex) if_nametoindex(interface);
 
1554
    if(if_index == 0){
 
1555
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1556
      exitcode = EX_UNAVAILABLE;
 
1557
      goto end;
 
1558
    }
 
1559
    
 
1560
    if(quit_now){
 
1561
      goto end;
 
1562
    }
 
1563
    
 
1564
    /* Re-raise priviliges */
 
1565
    errno = 0;
 
1566
    ret = seteuid(0);
 
1567
    if(ret == -1){
 
1568
      perror_plus("seteuid");
 
1569
    }
 
1570
    
 
1571
#ifdef __linux__
 
1572
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
 
1573
       messages about the network interface to mess up the prompt */
 
1574
    ret = klogctl(8, NULL, 5);
 
1575
    bool restore_loglevel = true;
 
1576
    if(ret == -1){
 
1577
      restore_loglevel = false;
 
1578
      perror_plus("klogctl");
 
1579
    }
 
1580
#endif  /* __linux__ */
 
1581
    
 
1582
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
 
1583
    if(sd < 0){
 
1584
      perror_plus("socket");
 
1585
      exitcode = EX_OSERR;
 
1586
#ifdef __linux__
 
1587
      if(restore_loglevel){
 
1588
        ret = klogctl(7, NULL, 0);
 
1589
        if(ret == -1){
 
1590
          perror_plus("klogctl");
 
1591
        }
 
1592
      }
 
1593
#endif  /* __linux__ */
 
1594
      /* Lower privileges */
 
1595
      errno = 0;
 
1596
      ret = seteuid(uid);
 
1597
      if(ret == -1){
 
1598
        perror_plus("seteuid");
 
1599
      }
 
1600
      goto end;
 
1601
    }
 
1602
    strcpy(network.ifr_name, interface);
 
1603
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1604
    if(ret == -1){
 
1605
      perror_plus("ioctl SIOCGIFFLAGS");
 
1606
#ifdef __linux__
 
1607
      if(restore_loglevel){
 
1608
        ret = klogctl(7, NULL, 0);
 
1609
        if(ret == -1){
 
1610
          perror_plus("klogctl");
 
1611
        }
 
1612
      }
 
1613
#endif  /* __linux__ */
 
1614
      exitcode = EX_OSERR;
 
1615
      /* Lower privileges */
 
1616
      errno = 0;
 
1617
      ret = seteuid(uid);
 
1618
      if(ret == -1){
 
1619
        perror_plus("seteuid");
 
1620
      }
 
1621
      goto end;
 
1622
    }
 
1623
    if((network.ifr_flags & IFF_UP) == 0){
 
1624
      network.ifr_flags |= IFF_UP;
 
1625
      take_down_interface = true;
 
1626
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1627
      if(ret == -1){
 
1628
        take_down_interface = false;
 
1629
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
 
1630
        exitcode = EX_OSERR;
 
1631
#ifdef __linux__
 
1632
        if(restore_loglevel){
 
1633
          ret = klogctl(7, NULL, 0);
 
1634
          if(ret == -1){
 
1635
            perror_plus("klogctl");
 
1636
          }
 
1637
        }
 
1638
#endif  /* __linux__ */
 
1639
        /* Lower privileges */
 
1640
        errno = 0;
 
1641
        ret = seteuid(uid);
 
1642
        if(ret == -1){
 
1643
          perror_plus("seteuid");
 
1644
        }
 
1645
        goto end;
 
1646
      }
 
1647
    }
 
1648
    /* sleep checking until interface is running. Check every 0.25s, up to total time of delay */
 
1649
    for(int i=0; i < delay * 4; i++){
 
1650
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1651
      if(ret == -1){
 
1652
        perror_plus("ioctl SIOCGIFFLAGS");
 
1653
      } else if(network.ifr_flags & IFF_RUNNING){
 
1654
        break;
 
1655
      }
 
1656
      struct timespec sleeptime = { .tv_nsec = 250000000 };
 
1657
      ret = nanosleep(&sleeptime, NULL);
 
1658
      if(ret == -1 and errno != EINTR){
 
1659
        perror_plus("nanosleep");
 
1660
      }
 
1661
    }
 
1662
    if(not take_down_interface){
 
1663
      /* We won't need the socket anymore */
 
1664
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1665
      if(ret == -1){
 
1666
        perror_plus("close");
 
1667
      }
 
1668
    }
 
1669
#ifdef __linux__
 
1670
    if(restore_loglevel){
 
1671
      /* Restores kernel loglevel to default */
 
1672
      ret = klogctl(7, NULL, 0);
 
1673
      if(ret == -1){
 
1674
        perror_plus("klogctl");
 
1675
      }
 
1676
    }
 
1677
#endif  /* __linux__ */
 
1678
    /* Lower privileges */
 
1679
    errno = 0;
 
1680
    if(take_down_interface){
 
1681
      /* Lower privileges */
 
1682
      ret = seteuid(uid);
 
1683
      if(ret == -1){
 
1684
        perror_plus("seteuid");
 
1685
      }
2700
1686
    } else {
2701
 
      if(ret == 0){
2702
 
        free(direntries);
2703
 
      }
2704
 
      fprintf_plus(stderr, "Could not find a network interface\n");
2705
 
      exitcode = EXIT_FAILURE;
2706
 
      goto end;
2707
 
    }
2708
 
  }
2709
 
  
2710
 
  /* Bring up interfaces which are down, and remove any "none"s */
2711
 
  {
2712
 
    char *interface = NULL;
2713
 
    while((interface = argz_next(mc.interfaces, mc.interfaces_size,
2714
 
                                 interface))){
2715
 
      /* If interface name is "none", stop bringing up interfaces.
2716
 
         Also remove all instances of "none" from the list */
2717
 
      if(strcmp(interface, "none") == 0){
2718
 
        argz_delete(&mc.interfaces, &mc.interfaces_size,
2719
 
                    interface);
2720
 
        interface = NULL;
2721
 
        while((interface = argz_next(mc.interfaces,
2722
 
                                     mc.interfaces_size, interface))){
2723
 
          if(strcmp(interface, "none") == 0){
2724
 
            argz_delete(&mc.interfaces, &mc.interfaces_size,
2725
 
                        interface);
2726
 
            interface = NULL;
2727
 
          }
2728
 
        }
2729
 
        break;
2730
 
      }
2731
 
      bool interface_was_up = interface_is_up(interface);
2732
 
      errno = bring_up_interface(interface, delay);
2733
 
      if(not interface_was_up){
2734
 
        if(errno != 0){
2735
 
          fprintf_plus(stderr, "Failed to bring up interface \"%s\":"
2736
 
                       " %s\n", interface, strerror(errno));
2737
 
        } else {
2738
 
          errno = argz_add(&interfaces_to_take_down,
2739
 
                           &interfaces_to_take_down_size,
2740
 
                           interface);
2741
 
          if(errno != 0){
2742
 
            perror_plus("argz_add");
2743
 
          }
2744
 
        }
2745
 
      }
2746
 
    }
2747
 
    if(debug and (interfaces_to_take_down == NULL)){
2748
 
      fprintf_plus(stderr, "No interfaces were brought up\n");
2749
 
    }
2750
 
  }
2751
 
  
2752
 
  /* If we only got one interface, explicitly use only that one */
2753
 
  if(argz_count(mc.interfaces, mc.interfaces_size) == 1){
2754
 
    if(debug){
2755
 
      fprintf_plus(stderr, "Using only interface \"%s\"\n",
2756
 
                   mc.interfaces);
2757
 
    }
2758
 
    if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces);
 
1687
      /* Lower privileges permanently */
 
1688
      ret = setuid(uid);
 
1689
      if(ret == -1){
 
1690
        perror_plus("setuid");
 
1691
      }
 
1692
    }
2759
1693
  }
2760
1694
  
2761
1695
  if(quit_now){
2762
1696
    goto end;
2763
1697
  }
2764
1698
  
2765
 
  ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc);
 
1699
  ret = init_gnutls_global(pubkey, seckey);
2766
1700
  if(ret == -1){
2767
 
    fprintf_plus(stderr, "init_gnutls_global failed\n");
 
1701
    fprintf(stderr, "init_gnutls_global failed\n");
2768
1702
    exitcode = EX_UNAVAILABLE;
2769
1703
    goto end;
2770
1704
  } else {
2775
1709
    goto end;
2776
1710
  }
2777
1711
  
2778
 
  /* Try /run/tmp before /tmp */
2779
 
  tempdir = mkdtemp(run_tempdir);
2780
 
  if(tempdir == NULL and errno == ENOENT){
2781
 
      if(debug){
2782
 
        fprintf_plus(stderr, "Tempdir %s did not work, trying %s\n",
2783
 
                     run_tempdir, old_tempdir);
2784
 
      }
2785
 
      tempdir = mkdtemp(old_tempdir);
2786
 
  }
2787
 
  if(tempdir == NULL){
 
1712
  if(mkdtemp(tempdir) == NULL){
2788
1713
    perror_plus("mkdtemp");
2789
1714
    goto end;
2790
1715
  }
 
1716
  tempdir_created = true;
2791
1717
  
2792
1718
  if(quit_now){
2793
1719
    goto end;
2794
1720
  }
2795
1721
  
2796
 
  if(not init_gpgme(pubkey, seckey, tempdir, &mc)){
2797
 
    fprintf_plus(stderr, "init_gpgme failed\n");
 
1722
  if(not init_gpgme(pubkey, seckey, tempdir)){
 
1723
    fprintf(stderr, "init_gpgme failed\n");
2798
1724
    exitcode = EX_UNAVAILABLE;
2799
1725
    goto end;
2800
1726
  } else {
2809
1735
    /* Connect directly, do not use Zeroconf */
2810
1736
    /* (Mainly meant for debugging) */
2811
1737
    char *address = strrchr(connect_to, ':');
2812
 
    
2813
1738
    if(address == NULL){
2814
 
      fprintf_plus(stderr, "No colon in address\n");
 
1739
      fprintf(stderr, "No colon in address\n");
2815
1740
      exitcode = EX_USAGE;
2816
1741
      goto end;
2817
1742
    }
2820
1745
      goto end;
2821
1746
    }
2822
1747
    
2823
 
    in_port_t port;
 
1748
    uint16_t port;
2824
1749
    errno = 0;
2825
1750
    tmpmax = strtoimax(address+1, &tmp, 10);
2826
1751
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2827
 
       or tmpmax != (in_port_t)tmpmax){
2828
 
      fprintf_plus(stderr, "Bad port number\n");
 
1752
       or tmpmax != (uint16_t)tmpmax){
 
1753
      fprintf(stderr, "Bad port number\n");
2829
1754
      exitcode = EX_USAGE;
2830
1755
      goto end;
2831
1756
    }
2832
 
    
 
1757
  
2833
1758
    if(quit_now){
2834
1759
      goto end;
2835
1760
    }
2836
1761
    
2837
 
    port = (in_port_t)tmpmax;
 
1762
    port = (uint16_t)tmpmax;
2838
1763
    *address = '\0';
 
1764
    address = connect_to;
2839
1765
    /* Colon in address indicates IPv6 */
2840
1766
    int af;
2841
 
    if(strchr(connect_to, ':') != NULL){
 
1767
    if(strchr(address, ':') != NULL){
2842
1768
      af = AF_INET6;
2843
 
      /* Accept [] around IPv6 address - see RFC 5952 */
2844
 
      if(connect_to[0] == '[' and address[-1] == ']')
2845
 
        {
2846
 
          connect_to++;
2847
 
          address[-1] = '\0';
2848
 
        }
2849
1769
    } else {
2850
1770
      af = AF_INET;
2851
1771
    }
2852
 
    address = connect_to;
2853
1772
    
2854
1773
    if(quit_now){
2855
1774
      goto end;
2856
1775
    }
2857
 
    
 
1776
 
2858
1777
    while(not quit_now){
2859
 
      ret = start_mandos_communication(address, port, if_index, af,
2860
 
                                       &mc);
 
1778
      ret = start_mandos_communication(address, port, if_index, af);
2861
1779
      if(quit_now or ret == 0){
2862
1780
        break;
2863
1781
      }
2864
 
      if(debug){
2865
 
        fprintf_plus(stderr, "Retrying in %d seconds\n",
2866
 
                     (int)retry_interval);
2867
 
      }
2868
 
      sleep((unsigned int)retry_interval);
2869
 
    }
2870
 
    
2871
 
    if(not quit_now){
 
1782
      sleep((int)retry_interval or 1);
 
1783
    };
 
1784
 
 
1785
    if (not quit_now){
2872
1786
      exitcode = EXIT_SUCCESS;
2873
1787
    }
2874
 
    
 
1788
 
2875
1789
    goto end;
2876
1790
  }
2877
1791
  
2889
1803
    config.publish_domain = 0;
2890
1804
    
2891
1805
    /* Allocate a new server */
2892
 
    mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll),
2893
 
                                 &config, NULL, NULL, &ret_errno);
 
1806
    mc.server = avahi_server_new(avahi_simple_poll_get
 
1807
                                 (mc.simple_poll), &config, NULL,
 
1808
                                 NULL, &error);
2894
1809
    
2895
1810
    /* Free the Avahi configuration data */
2896
1811
    avahi_server_config_free(&config);
2898
1813
  
2899
1814
  /* Check if creating the Avahi server object succeeded */
2900
1815
  if(mc.server == NULL){
2901
 
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
2902
 
                 avahi_strerror(ret_errno));
 
1816
    fprintf(stderr, "Failed to create Avahi server: %s\n",
 
1817
            avahi_strerror(error));
2903
1818
    exitcode = EX_UNAVAILABLE;
2904
1819
    goto end;
2905
1820
  }
2911
1826
  /* Create the Avahi service browser */
2912
1827
  sb = avahi_s_service_browser_new(mc.server, if_index,
2913
1828
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2914
 
                                   NULL, 0, browse_callback,
2915
 
                                   (void *)&mc);
 
1829
                                   NULL, 0, browse_callback, NULL);
2916
1830
  if(sb == NULL){
2917
 
    fprintf_plus(stderr, "Failed to create service browser: %s\n",
2918
 
                 avahi_strerror(avahi_server_errno(mc.server)));
 
1831
    fprintf(stderr, "Failed to create service browser: %s\n",
 
1832
            avahi_strerror(avahi_server_errno(mc.server)));
2919
1833
    exitcode = EX_UNAVAILABLE;
2920
1834
    goto end;
2921
1835
  }
2927
1841
  /* Run the main loop */
2928
1842
  
2929
1843
  if(debug){
2930
 
    fprintf_plus(stderr, "Starting Avahi loop search\n");
 
1844
    fprintf(stderr, "Starting Avahi loop search\n");
2931
1845
  }
2932
 
  
2933
 
  ret = avahi_loop_with_timeout(simple_poll,
2934
 
                                (int)(retry_interval * 1000), &mc);
 
1846
 
 
1847
  ret = avahi_loop_with_timeout(mc.simple_poll, (int)(retry_interval * 1000));
2935
1848
  if(debug){
2936
 
    fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n",
2937
 
                 (ret == 0) ? "successfully" : "with error");
 
1849
    fprintf(stderr, "avahi_loop_with_timeout exited %s\n",
 
1850
            (ret == 0) ? "successfully" : "with error");
2938
1851
  }
2939
1852
  
2940
1853
 end:
2941
1854
  
2942
1855
  if(debug){
2943
 
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
 
1856
    fprintf(stderr, "%s exiting\n", argv[0]);
2944
1857
  }
2945
1858
  
2946
1859
  /* Cleanup things */
2947
 
  free(mc.interfaces);
2948
 
  
2949
1860
  if(sb != NULL)
2950
1861
    avahi_s_service_browser_free(sb);
2951
1862
  
2952
1863
  if(mc.server != NULL)
2953
1864
    avahi_server_free(mc.server);
2954
1865
  
2955
 
  if(simple_poll != NULL)
2956
 
    avahi_simple_poll_free(simple_poll);
 
1866
  if(mc.simple_poll != NULL)
 
1867
    avahi_simple_poll_free(mc.simple_poll);
2957
1868
  
2958
1869
  if(gnutls_initialized){
2959
1870
    gnutls_certificate_free_credentials(mc.cred);
 
1871
    gnutls_global_deinit();
2960
1872
    gnutls_dh_params_deinit(mc.dh_params);
2961
1873
  }
2962
1874
  
2963
1875
  if(gpgme_initialized){
2964
1876
    gpgme_release(mc.ctx);
2965
1877
  }
2966
 
  
2967
 
  /* Cleans up the circular linked list of Mandos servers the client
2968
 
     has seen */
 
1878
 
 
1879
  /* cleans up the circular linked list of mandos servers the client has seen */
2969
1880
  if(mc.current_server != NULL){
2970
1881
    mc.current_server->prev->next = NULL;
2971
1882
    while(mc.current_server != NULL){
2972
1883
      server *next = mc.current_server->next;
2973
 
#ifdef __GNUC__
2974
 
#pragma GCC diagnostic push
2975
 
#pragma GCC diagnostic ignored "-Wcast-qual"
2976
 
#endif
2977
 
      free((char *)(mc.current_server->ip));
2978
 
#ifdef __GNUC__
2979
 
#pragma GCC diagnostic pop
2980
 
#endif
2981
1884
      free(mc.current_server);
2982
1885
      mc.current_server = next;
2983
1886
    }
2984
1887
  }
2985
1888
  
2986
 
  /* Re-raise privileges */
2987
 
  {
2988
 
    ret_errno = raise_privileges();
2989
 
    if(ret_errno != 0){
2990
 
      errno = ret_errno;
2991
 
      perror_plus("Failed to raise privileges");
2992
 
    } else {
2993
 
      
2994
 
      /* Run network hooks */
2995
 
      run_network_hooks("stop", interfaces_hooks != NULL ?
2996
 
                        interfaces_hooks : "", delay);
2997
 
      
2998
 
      /* Take down the network interfaces which were brought up */
2999
 
      {
3000
 
        char *interface = NULL;
3001
 
        while((interface=argz_next(interfaces_to_take_down,
3002
 
                                   interfaces_to_take_down_size,
3003
 
                                   interface))){
3004
 
          ret_errno = take_down_interface(interface);
3005
 
          if(ret_errno != 0){
3006
 
            errno = ret_errno;
3007
 
            perror_plus("Failed to take down interface");
3008
 
          }
3009
 
        }
3010
 
        if(debug and (interfaces_to_take_down == NULL)){
3011
 
          fprintf_plus(stderr, "No interfaces needed to be taken"
3012
 
                       " down\n");
3013
 
        }
3014
 
      }
 
1889
  /* Take down the network interface */
 
1890
  if(take_down_interface){
 
1891
    /* Re-raise priviliges */
 
1892
    errno = 0;
 
1893
    ret = seteuid(0);
 
1894
    if(ret == -1){
 
1895
      perror_plus("seteuid");
3015
1896
    }
3016
 
    
3017
 
    ret_errno = lower_privileges_permanently();
3018
 
    if(ret_errno != 0){
3019
 
      errno = ret_errno;
3020
 
      perror_plus("Failed to lower privileges permanently");
 
1897
    if(geteuid() == 0){
 
1898
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
 
1899
      if(ret == -1){
 
1900
        perror_plus("ioctl SIOCGIFFLAGS");
 
1901
      } else if(network.ifr_flags & IFF_UP) {
 
1902
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1903
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
 
1904
        if(ret == -1){
 
1905
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1906
        }
 
1907
      }
 
1908
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
 
1909
      if(ret == -1){
 
1910
        perror_plus("close");
 
1911
      }
 
1912
      /* Lower privileges permanently */
 
1913
      errno = 0;
 
1914
      ret = setuid(uid);
 
1915
      if(ret == -1){
 
1916
        perror_plus("setuid");
 
1917
      }
3021
1918
    }
3022
1919
  }
3023
1920
  
3024
 
  free(interfaces_to_take_down);
3025
 
  free(interfaces_hooks);
3026
 
  
3027
1921
  /* Removes the GPGME temp directory and all files inside */
3028
 
  if(tempdir != NULL){
 
1922
  if(tempdir_created){
3029
1923
    struct dirent **direntries = NULL;
3030
 
    int tempdir_fd = (int)TEMP_FAILURE_RETRY(open(tempdir, O_RDONLY
3031
 
                                                  | O_NOFOLLOW
3032
 
                                                  | O_DIRECTORY
3033
 
                                                  | O_PATH));
3034
 
    if(tempdir_fd == -1){
3035
 
      perror_plus("open");
3036
 
    } else {
3037
 
      int numentries = scandirat(tempdir_fd, ".", &direntries,
3038
 
                                 notdotentries, alphasort);
3039
 
      if(numentries >= 0){
3040
 
        for(int i = 0; i < numentries; i++){
3041
 
          ret = unlinkat(tempdir_fd, direntries[i]->d_name, 0);
3042
 
          if(ret == -1){
3043
 
            fprintf_plus(stderr, "unlinkat(open(\"%s\", O_RDONLY),"
3044
 
                         " \"%s\", 0): %s\n", tempdir,
3045
 
                         direntries[i]->d_name, strerror(errno));
3046
 
          }
3047
 
          free(direntries[i]);
3048
 
        }
3049
 
        
3050
 
        /* need to clean even if 0 because man page doesn't specify */
3051
 
        free(direntries);
3052
 
        if(numentries == -1){
3053
 
          perror_plus("scandir");
3054
 
        }
3055
 
        ret = rmdir(tempdir);
3056
 
        if(ret == -1 and errno != ENOENT){
3057
 
          perror_plus("rmdir");
3058
 
        }
 
1924
    struct dirent *direntry = NULL;
 
1925
    ret = scandir(tempdir, &direntries, notdotentries, alphasort);
 
1926
    if (ret > 0){
 
1927
      for(int i = 0; i < ret; i++){
 
1928
        direntry = direntries[i];
 
1929
        char *fullname = NULL;
 
1930
        ret = asprintf(&fullname, "%s/%s", tempdir,
 
1931
                       direntry->d_name);
 
1932
        if(ret < 0){
 
1933
          perror_plus("asprintf");
 
1934
          continue;
 
1935
        }
 
1936
        ret = remove(fullname);
 
1937
        if(ret == -1){
 
1938
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1939
                  strerror(errno));
 
1940
        }
 
1941
        free(fullname);
3059
1942
      }
3060
 
      close(tempdir_fd);
 
1943
    }
 
1944
 
 
1945
    /* need to be cleaned even if ret == 0 because man page dont specify */
 
1946
    free(direntries);
 
1947
    if (ret == -1){
 
1948
      perror_plus("scandir");
 
1949
    }
 
1950
    ret = rmdir(tempdir);
 
1951
    if(ret == -1 and errno != ENOENT){
 
1952
      perror_plus("rmdir");
3061
1953
    }
3062
1954
  }
3063
1955