/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: 2012-06-07 21:00:57 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120607210057-9k4mou58uht7sj2m
* plugins.d/mandos-client.c (bring_up_interface): Bug fix: Return
                                                  errno code.  Don't
                                                  modify errno.

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