/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 at bsnet
  • Date: 2011-12-25 00:40:09 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111225004009-n5uimmac6h8djtv8
* plugin-runner.c (add_to_char_array): Added "nonnull" attribute.
  (add_argument): Added "nonnull" attribute on the "arg" argument.
  (add_environment): Added "nonnull" attribute on the "def" argument.
  (print_out_password, free_plugin): Added "nonnull" attribute.
  (main/parse_opt): Added "nonnull" attribute on the "state" argument.
* plugins.d/mandos-client.c (perror_plus): Bug fix; restore errno
                                           after fprintf().
* plugins.d/password-prompt.c (fprintf_plus): New.
 (conflict_detection/is_plymouth, main/parse_opt): Added "nonnull"
                                                   attribute.
 (conflict_detection/is_plymouth, conflict_detection, main): Bug fix;
                                                             Call
                                                             error_plus()
                                                             instead
                                                             of
                                                             error().
  (main/parse_opt): Added "nonnull" attribute on the "state" argument.
* plugins.d/plymouth.c (exec_and_wait): Added "nonnull" attribute on
                                        the "path" and "argv"
                                        arguments.
  (is_plymouth): Added "nonnull" attribute.

Show diffs side-by-side

added added

removed removed

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