/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-05-26 22:56:38 UTC
  • mfrom: (589.1.1 socket-option)
  • Revision ID: teddy@recompile.se-20120526225638-4hvqyrvmj0036lfn
Merge "--socket" option for server.

This is suggested by the GNU Coding Standards' Table of Long Options,
and will probably also allow socket activation (e.g. by systemd(8)).

Show diffs side-by-side

added added

removed removed

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