/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2009-09-07 07:48:59 UTC
  • Revision ID: teddy@fukt.bsnet.se-20090907074859-nv2nni1wwib5hi10
* plugin-runner.c: Minor stylistic changes.

* plugins.d/askpass-fifo.c: Changed contact information and did minor
                            stylistic changes.

* plugins.d/mandos-client.c: Minor stylistic changes.

* plugins.d/password-prompt.c: Changed contact information.

* plugins.d/splashy.c: Changed contact information.
  (main): Changed error handling design.  Bug fix: Will now be much
          more tolerant against signals.  Bug fix: Will now re-raise
          signal received.

* plugins.d/usplash.c: Changed contact information and did minor
                       stylistic changes.

Show diffs side-by-side

added added

removed removed

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