/mandos/trunk

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

« back to all changes in this revision

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

  • Committer: Teddy Hogeborn
  • Date: 2012-06-09 23:41:07 UTC
  • mto: This revision was merged to the branch mainline in revision 596.
  • Revision ID: teddy@recompile.se-20120609234107-vm6zilzz0y6aihsm
* plugins.d/mandos-client.c (raise_privileges,
  raise_privileges_permanently, lower_privileges): Return error_t and
                                                   save old errno
                                                   before calling any
                                                   other function.

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