/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-02-13 05:38:21 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090213053821-03e696gckk4nbjps
Support not using IPv6 in server:

* mandos (AvahiService.__init__): Take new "protocol" parameter.  All
                                  callers changed.
  (IPv6_TCPServer.__init__): Take new "use_ipv6" parameter.  All
                             callers changed.
  (IPv6_TCPServer.server_bind): Create IPv4 socket if not using IPv6.
  (main): New "--no-ipv6" command line option.  New "use_ipv6" config
          option.
* mandos-options.xml ([@id="address"]): Document conditional IPv4
                                        address support.
  ([@id="ipv6"]): New paragraph.
* mandos.conf (use_ipv6): New config option.
* mandos.conf.xml (OPTIONS): Document new "use_dbus" option.
  (EXAMPLE): Changed to use IPv6 link-local address.  Added "use_ipv6"
             option.
* mandos.xml (SYNOPSIS): New "--no-ipv6" option.
  (OPTIONS): Document new "--no-ipv6" option.

Show diffs side-by-side

added added

removed removed

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