/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 at bsnet
  • Date: 2011-12-24 23:17:02 UTC
  • Revision ID: teddy@fukt.bsnet.se-20111224231702-1ffgu6r02p0bz9co
* plugins.d/splashy.c (error_plus): Check format string.
* plugins.d/askpass-fifo.c (error_plus): - '' -
* plugins.d/plymouth.c (error_plus): - '' -
* plugins.d/password-prompt.c (error_plus): - '' -
* plugins.d/usplash.c (error_plus): - '' -

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