/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

* plugins.d/mandos-client.c: Merge unified printing system.

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