/mandos/release

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/release

« back to all changes in this revision

Viewing changes to plugins.d/mandos-client.c

  • Committer: Teddy Hogeborn
  • Date: 2014-06-15 02:48:49 UTC
  • mto: (237.7.272 trunk)
  • mto: This revision was merged to the branch mainline in revision 317.
  • Revision ID: teddy@recompile.se-20140615024849-68x3q8g4yzadl33s
mandos: New "--no-zeroconf" option.  Also make "--socket=0" work.

* mandos (main): New "--no-zeroconf" option.  Also do not interpret
                 socket=0 as no socket.
* mandos-options.xml (zeroconf): New.
* mandos.conf (socket, zeroconf): New.
* mandos.xml (SYNOPSIS, OPTIONS): Added "--no-zeroconf".

Show diffs side-by-side

added added

removed removed

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