/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2014-06-13 22:13:56 UTC
  • Revision ID: teddy@recompile.se-20140613221356-b9c36ctxmw4pelja
Fix free() of possibly uninitialized pointer in mandos-client.

* plugins.d/mandos-client (main): Initialize "direntries" to NULL so
                                  it can be free()'d even if scandir()
                                  fails.

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