/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-07 20:29:36 UTC
  • Revision ID: teddy@recompile.se-20140607202936-crh5fxrdd804oora
Fix typo in code comment.

* debian/mandos.postinst: Fix typo in comment.

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