/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: Björn Påhlsson
  • Date: 2011-11-24 20:17:38 UTC
  • mfrom: (505.3.10 client-network-hooks)
  • mto: This revision was merged to the branch mainline in revision 525.
  • Revision ID: belorn@fukt.bsnet.se-20111124201738-tjjpqg75110ocwdt
merge

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-2010 Teddy Hogeborn
13
 
 * Copyright © 2008-2010 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 */
 
65
#include <errno.h>              /* perror(), errno,
 
66
                                   program_invocation_short_name */
66
67
#include <time.h>               /* nanosleep(), time(), sleep() */
67
68
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
68
69
                                   SIOCSIFFLAGS, if_indextoname(),
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>";
130
134
static const char sys_class_net[] = "/sys/class/net";
131
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;
132
148
 
133
149
/* Used for passing in values through the Avahi callback functions */
134
150
typedef struct {
139
155
  gnutls_dh_params_t dh_params;
140
156
  const char *priority;
141
157
  gpgme_ctx_t ctx;
 
158
  server *current_server;
142
159
} mandos_context;
143
160
 
144
161
/* global context so signal handler can reach it*/
145
162
mandos_context mc = { .simple_poll = NULL, .server = NULL,
146
163
                      .dh_bits = 1024, .priority = "SECURE256"
147
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
 
164
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
 
165
                      .current_server = NULL };
148
166
 
149
167
sig_atomic_t quit_now = 0;
150
168
int signal_received = 0;
151
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
 
152
186
/*
153
187
 * Make additional room in "buffer" for at least BUFFER_SIZE more
154
188
 * bytes. "buffer_capacity" is how much is currently allocated,
155
189
 * "buffer_length" is how much is already used.
156
190
 */
157
191
size_t incbuffer(char **buffer, size_t buffer_length,
158
 
                  size_t buffer_capacity){
 
192
                 size_t buffer_capacity){
159
193
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
160
194
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
161
195
    if(buffer == NULL){
166
200
  return buffer_capacity;
167
201
}
168
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
 
169
240
/* 
170
241
 * Initialize GPGME.
171
242
 */
172
 
static bool init_gpgme(const char *seckey,
173
 
                       const char *pubkey, const char *tempdir){
 
243
static bool init_gpgme(const char *seckey, const char *pubkey,
 
244
                       const char *tempdir){
174
245
  gpgme_error_t rc;
175
246
  gpgme_engine_info_t engine_info;
176
247
  
185
256
    
186
257
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
187
258
    if(fd == -1){
188
 
      perror("open");
 
259
      perror_plus("open");
189
260
      return false;
190
261
    }
191
262
    
192
263
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
193
264
    if(rc != GPG_ERR_NO_ERROR){
194
 
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
195
 
              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));
196
267
      return false;
197
268
    }
198
269
    
199
270
    rc = gpgme_op_import(mc.ctx, pgp_data);
200
271
    if(rc != GPG_ERR_NO_ERROR){
201
 
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
202
 
              gpgme_strsource(rc), gpgme_strerror(rc));
 
272
      fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n",
 
273
                   gpgme_strsource(rc), gpgme_strerror(rc));
203
274
      return false;
204
275
    }
205
276
    
206
277
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
207
278
    if(ret == -1){
208
 
      perror("close");
 
279
      perror_plus("close");
209
280
    }
210
281
    gpgme_data_release(pgp_data);
211
282
    return true;
212
283
  }
213
284
  
214
285
  if(debug){
215
 
    fprintf(stderr, "Initializing GPGME\n");
 
286
    fprintf_plus(stderr, "Initializing GPGME\n");
216
287
  }
217
288
  
218
289
  /* Init GPGME */
219
290
  gpgme_check_version(NULL);
220
291
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
221
292
  if(rc != GPG_ERR_NO_ERROR){
222
 
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
223
 
            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));
224
295
    return false;
225
296
  }
226
297
  
227
 
    /* Set GPGME home directory for the OpenPGP engine only */
 
298
  /* Set GPGME home directory for the OpenPGP engine only */
228
299
  rc = gpgme_get_engine_info(&engine_info);
229
300
  if(rc != GPG_ERR_NO_ERROR){
230
 
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
231
 
            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));
232
303
    return false;
233
304
  }
234
305
  while(engine_info != NULL){
240
311
    engine_info = engine_info->next;
241
312
  }
242
313
  if(engine_info == NULL){
243
 
    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);
244
316
    return false;
245
317
  }
246
318
  
247
319
  /* Create new GPGME "context" */
248
320
  rc = gpgme_new(&(mc.ctx));
249
321
  if(rc != GPG_ERR_NO_ERROR){
250
 
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
251
 
            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));
252
325
    return false;
253
326
  }
254
327
  
273
346
  ssize_t plaintext_length = 0;
274
347
  
275
348
  if(debug){
276
 
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
 
349
    fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n");
277
350
  }
278
351
  
279
352
  /* Create new GPGME data buffer from memory cryptotext */
280
353
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
281
354
                               0);
282
355
  if(rc != GPG_ERR_NO_ERROR){
283
 
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
284
 
            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));
285
358
    return -1;
286
359
  }
287
360
  
288
361
  /* Create new empty GPGME data buffer for the plaintext */
289
362
  rc = gpgme_data_new(&dh_plain);
290
363
  if(rc != GPG_ERR_NO_ERROR){
291
 
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
292
 
            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));
293
367
    gpgme_data_release(dh_crypto);
294
368
    return -1;
295
369
  }
298
372
     data buffer */
299
373
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
300
374
  if(rc != GPG_ERR_NO_ERROR){
301
 
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
302
 
            gpgme_strsource(rc), gpgme_strerror(rc));
 
375
    fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n",
 
376
                 gpgme_strsource(rc), gpgme_strerror(rc));
303
377
    plaintext_length = -1;
304
378
    if(debug){
305
379
      gpgme_decrypt_result_t result;
306
380
      result = gpgme_op_decrypt_result(mc.ctx);
307
381
      if(result == NULL){
308
 
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
 
382
        fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n");
309
383
      } else {
310
 
        fprintf(stderr, "Unsupported algorithm: %s\n",
311
 
                result->unsupported_algorithm);
312
 
        fprintf(stderr, "Wrong key usage: %u\n",
313
 
                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);
314
388
        if(result->file_name != NULL){
315
 
          fprintf(stderr, "File name: %s\n", result->file_name);
 
389
          fprintf_plus(stderr, "File name: %s\n", result->file_name);
316
390
        }
317
391
        gpgme_recipient_t recipient;
318
392
        recipient = result->recipients;
319
393
        while(recipient != NULL){
320
 
          fprintf(stderr, "Public key algorithm: %s\n",
321
 
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
322
 
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
323
 
          fprintf(stderr, "Secret key available: %s\n",
324
 
                  recipient->status == GPG_ERR_NO_SECKEY
325
 
                  ? "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");
326
401
          recipient = recipient->next;
327
402
        }
328
403
      }
331
406
  }
332
407
  
333
408
  if(debug){
334
 
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
 
409
    fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n");
335
410
  }
336
411
  
337
412
  /* Seek back to the beginning of the GPGME plaintext data buffer */
338
413
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
339
 
    perror("gpgme_data_seek");
 
414
    perror_plus("gpgme_data_seek");
340
415
    plaintext_length = -1;
341
416
    goto decrypt_end;
342
417
  }
344
419
  *plaintext = NULL;
345
420
  while(true){
346
421
    plaintext_capacity = incbuffer(plaintext,
347
 
                                      (size_t)plaintext_length,
348
 
                                      plaintext_capacity);
 
422
                                   (size_t)plaintext_length,
 
423
                                   plaintext_capacity);
349
424
    if(plaintext_capacity == 0){
350
 
        perror("incbuffer");
351
 
        plaintext_length = -1;
352
 
        goto decrypt_end;
 
425
      perror_plus("incbuffer");
 
426
      plaintext_length = -1;
 
427
      goto decrypt_end;
353
428
    }
354
429
    
355
430
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
360
435
      break;
361
436
    }
362
437
    if(ret < 0){
363
 
      perror("gpgme_data_read");
 
438
      perror_plus("gpgme_data_read");
364
439
      plaintext_length = -1;
365
440
      goto decrypt_end;
366
441
    }
368
443
  }
369
444
  
370
445
  if(debug){
371
 
    fprintf(stderr, "Decrypted password is: ");
 
446
    fprintf_plus(stderr, "Decrypted password is: ");
372
447
    for(ssize_t i = 0; i < plaintext_length; i++){
373
448
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
374
449
    }
396
471
/* GnuTLS log function callback */
397
472
static void debuggnutls(__attribute__((unused)) int level,
398
473
                        const char* string){
399
 
  fprintf(stderr, "GnuTLS: %s", string);
 
474
  fprintf_plus(stderr, "GnuTLS: %s", string);
400
475
}
401
476
 
402
477
static int init_gnutls_global(const char *pubkeyfilename,
404
479
  int ret;
405
480
  
406
481
  if(debug){
407
 
    fprintf(stderr, "Initializing GnuTLS\n");
 
482
    fprintf_plus(stderr, "Initializing GnuTLS\n");
408
483
  }
409
484
  
410
485
  ret = gnutls_global_init();
411
486
  if(ret != GNUTLS_E_SUCCESS){
412
 
    fprintf(stderr, "GnuTLS global_init: %s\n",
413
 
            safer_gnutls_strerror(ret));
 
487
    fprintf_plus(stderr, "GnuTLS global_init: %s\n",
 
488
                 safer_gnutls_strerror(ret));
414
489
    return -1;
415
490
  }
416
491
  
423
498
  }
424
499
  
425
500
  /* OpenPGP credentials */
426
 
  gnutls_certificate_allocate_credentials(&mc.cred);
 
501
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
427
502
  if(ret != GNUTLS_E_SUCCESS){
428
 
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
429
 
                                                    from
430
 
                                                    -Wunreachable-code
431
 
                                                 */
432
 
            safer_gnutls_strerror(ret));
 
503
    fprintf_plus(stderr, "GnuTLS memory error: %s\n",
 
504
                 safer_gnutls_strerror(ret));
433
505
    gnutls_global_deinit();
434
506
    return -1;
435
507
  }
436
508
  
437
509
  if(debug){
438
 
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
439
 
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
440
 
            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);
441
514
  }
442
515
  
443
516
  ret = gnutls_certificate_set_openpgp_key_file
444
517
    (mc.cred, pubkeyfilename, seckeyfilename,
445
518
     GNUTLS_OPENPGP_FMT_BASE64);
446
519
  if(ret != GNUTLS_E_SUCCESS){
447
 
    fprintf(stderr,
448
 
            "Error[%d] while reading the OpenPGP key pair ('%s',"
449
 
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
450
 
    fprintf(stderr, "The GnuTLS error is: %s\n",
451
 
            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));
452
525
    goto globalfail;
453
526
  }
454
527
  
455
528
  /* GnuTLS server initialization */
456
529
  ret = gnutls_dh_params_init(&mc.dh_params);
457
530
  if(ret != GNUTLS_E_SUCCESS){
458
 
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
459
 
            " %s\n", safer_gnutls_strerror(ret));
 
531
    fprintf_plus(stderr, "Error in GnuTLS DH parameter"
 
532
                 " initialization: %s\n",
 
533
                 safer_gnutls_strerror(ret));
460
534
    goto globalfail;
461
535
  }
462
536
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
463
537
  if(ret != GNUTLS_E_SUCCESS){
464
 
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
465
 
            safer_gnutls_strerror(ret));
 
538
    fprintf_plus(stderr, "Error in GnuTLS prime generation: %s\n",
 
539
                 safer_gnutls_strerror(ret));
466
540
    goto globalfail;
467
541
  }
468
542
  
488
562
    }
489
563
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
490
564
  if(ret != GNUTLS_E_SUCCESS){
491
 
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
492
 
            safer_gnutls_strerror(ret));
 
565
    fprintf_plus(stderr,
 
566
                 "Error in GnuTLS session initialization: %s\n",
 
567
                 safer_gnutls_strerror(ret));
493
568
  }
494
569
  
495
570
  {
502
577
      }
503
578
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
504
579
    if(ret != GNUTLS_E_SUCCESS){
505
 
      fprintf(stderr, "Syntax error at: %s\n", err);
506
 
      fprintf(stderr, "GnuTLS error: %s\n",
507
 
              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));
508
583
      gnutls_deinit(*session);
509
584
      return -1;
510
585
    }
519
594
    }
520
595
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
521
596
  if(ret != GNUTLS_E_SUCCESS){
522
 
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
523
 
            safer_gnutls_strerror(ret));
 
597
    fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n",
 
598
                 safer_gnutls_strerror(ret));
524
599
    gnutls_deinit(*session);
525
600
    return -1;
526
601
  }
571
646
    pf = PF_INET;
572
647
    break;
573
648
  default:
574
 
    fprintf(stderr, "Bad address family: %d\n", af);
 
649
    fprintf_plus(stderr, "Bad address family: %d\n", af);
575
650
    errno = EINVAL;
576
651
    return -1;
577
652
  }
582
657
  }
583
658
  
584
659
  if(debug){
585
 
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
586
 
            "\n", ip, port);
 
660
    fprintf_plus(stderr, "Setting up a TCP connection to %s, port %"
 
661
                 PRIu16 "\n", ip, port);
587
662
  }
588
663
  
589
664
  tcp_sd = socket(pf, SOCK_STREAM, 0);
590
665
  if(tcp_sd < 0){
591
666
    int e = errno;
592
 
    perror("socket");
 
667
    perror_plus("socket");
593
668
    errno = e;
594
669
    goto mandos_end;
595
670
  }
609
684
  }
610
685
  if(ret < 0 ){
611
686
    int e = errno;
612
 
    perror("inet_pton");
 
687
    perror_plus("inet_pton");
613
688
    errno = e;
614
689
    goto mandos_end;
615
690
  }
616
691
  if(ret == 0){
617
692
    int e = errno;
618
 
    fprintf(stderr, "Bad address: %s\n", ip);
 
693
    fprintf_plus(stderr, "Bad address: %s\n", ip);
619
694
    errno = e;
620
695
    goto mandos_end;
621
696
  }
626
701
    
627
702
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
628
703
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
629
 
                              -Wunreachable-code*/
 
704
                                -Wunreachable-code*/
630
705
      if(if_index == AVAHI_IF_UNSPEC){
631
 
        fprintf(stderr, "An IPv6 link-local address is incomplete"
632
 
                " without a network interface\n");
 
706
        fprintf_plus(stderr, "An IPv6 link-local address is"
 
707
                     " incomplete without a network interface\n");
633
708
        errno = EINVAL;
634
709
        goto mandos_end;
635
710
      }
651
726
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
652
727
      char interface[IF_NAMESIZE];
653
728
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
654
 
        perror("if_indextoname");
 
729
        perror_plus("if_indextoname");
655
730
      } else {
656
 
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
657
 
                ip, interface, port);
 
731
        fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIu16
 
732
                     "\n", ip, interface, port);
658
733
      }
659
734
    } else {
660
 
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
661
 
              port);
 
735
      fprintf_plus(stderr, "Connection to: %s, port %" PRIu16 "\n",
 
736
                   ip, port);
662
737
    }
663
738
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
664
739
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
671
746
                        sizeof(addrstr));
672
747
    }
673
748
    if(pcret == NULL){
674
 
      perror("inet_ntop");
 
749
      perror_plus("inet_ntop");
675
750
    } else {
676
751
      if(strcmp(addrstr, ip) != 0){
677
 
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
 
752
        fprintf_plus(stderr, "Canonical address form: %s\n", addrstr);
678
753
      }
679
754
    }
680
755
  }
692
767
  if(ret < 0){
693
768
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
694
769
      int e = errno;
695
 
      perror("connect");
 
770
      perror_plus("connect");
696
771
      errno = e;
697
772
    }
698
773
    goto mandos_end;
708
783
  while(true){
709
784
    size_t out_size = strlen(out);
710
785
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
711
 
                                   out_size - written));
 
786
                                        out_size - written));
712
787
    if(ret == -1){
713
788
      int e = errno;
714
 
      perror("write");
 
789
      perror_plus("write");
715
790
      errno = e;
716
791
      goto mandos_end;
717
792
    }
734
809
  }
735
810
  
736
811
  if(debug){
737
 
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
 
812
    fprintf_plus(stderr, "Establishing TLS session with %s\n", ip);
738
813
  }
739
814
  
740
815
  if(quit_now){
742
817
    goto mandos_end;
743
818
  }
744
819
  
 
820
  /* Spurious warning from -Wint-to-pointer-cast */
745
821
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
746
822
  
747
823
  if(quit_now){
759
835
  
760
836
  if(ret != GNUTLS_E_SUCCESS){
761
837
    if(debug){
762
 
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
 
838
      fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n");
763
839
      gnutls_perror(ret);
764
840
    }
765
841
    errno = EPROTO;
769
845
  /* Read OpenPGP packet that contains the wanted password */
770
846
  
771
847
  if(debug){
772
 
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
773
 
            ip);
 
848
    fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from"
 
849
                 " %s\n", ip);
774
850
  }
775
851
  
776
852
  while(true){
781
857
    }
782
858
    
783
859
    buffer_capacity = incbuffer(&buffer, buffer_length,
784
 
                                   buffer_capacity);
 
860
                                buffer_capacity);
785
861
    if(buffer_capacity == 0){
786
862
      int e = errno;
787
 
      perror("incbuffer");
 
863
      perror_plus("incbuffer");
788
864
      errno = e;
789
865
      goto mandos_end;
790
866
    }
814
890
          }
815
891
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
816
892
        if(ret < 0){
817
 
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
 
893
          fprintf_plus(stderr, "*** GnuTLS Re-handshake failed "
 
894
                       "***\n");
818
895
          gnutls_perror(ret);
819
896
          errno = EPROTO;
820
897
          goto mandos_end;
821
898
        }
822
899
        break;
823
900
      default:
824
 
        fprintf(stderr, "Unknown error while reading data from"
825
 
                " encrypted session with Mandos server\n");
 
901
        fprintf_plus(stderr, "Unknown error while reading data from"
 
902
                     " encrypted session with Mandos server\n");
826
903
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
827
904
        errno = EIO;
828
905
        goto mandos_end;
833
910
  }
834
911
  
835
912
  if(debug){
836
 
    fprintf(stderr, "Closing TLS session\n");
 
913
    fprintf_plus(stderr, "Closing TLS session\n");
837
914
  }
838
915
  
839
916
  if(quit_now){
851
928
  
852
929
  if(buffer_length > 0){
853
930
    ssize_t decrypted_buffer_size;
854
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
855
 
                                               buffer_length,
 
931
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
856
932
                                               &decrypted_buffer);
857
933
    if(decrypted_buffer_size >= 0){
858
934
      
869
945
        if(ret == 0 and ferror(stdout)){
870
946
          int e = errno;
871
947
          if(debug){
872
 
            fprintf(stderr, "Error writing encrypted data: %s\n",
873
 
                    strerror(errno));
 
948
            fprintf_plus(stderr, "Error writing encrypted data: %s\n",
 
949
                         strerror(errno));
874
950
          }
875
951
          errno = e;
876
952
          goto mandos_end;
895
971
      if(e == 0){
896
972
        e = errno;
897
973
      }
898
 
      perror("close");
 
974
      perror_plus("close");
899
975
    }
900
976
    gnutls_deinit(session);
 
977
    errno = e;
901
978
    if(quit_now){
902
 
      e = EINTR;
 
979
      errno = EINTR;
903
980
      retval = -1;
904
981
    }
905
 
    errno = e;
906
982
  }
907
983
  return retval;
908
984
}
933
1009
  switch(event){
934
1010
  default:
935
1011
  case AVAHI_RESOLVER_FAILURE:
936
 
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
937
 
            " of type '%s' in domain '%s': %s\n", name, type, domain,
938
 
            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)));
939
1016
    break;
940
1017
    
941
1018
  case AVAHI_RESOLVER_FOUND:
943
1020
      char ip[AVAHI_ADDRESS_STR_MAX];
944
1021
      avahi_address_snprint(ip, sizeof(ip), address);
945
1022
      if(debug){
946
 
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
947
 
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
948
 
                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);
949
1026
      }
950
1027
      int ret = start_mandos_communication(ip, port, interface,
951
1028
                                           avahi_proto_to_af(proto));
952
1029
      if(ret == 0){
953
1030
        avahi_simple_poll_quit(mc.simple_poll);
 
1031
      } else {
 
1032
        ret = add_server(ip, port, interface,
 
1033
                         avahi_proto_to_af(proto));
954
1034
      }
955
1035
    }
956
1036
  }
980
1060
  default:
981
1061
  case AVAHI_BROWSER_FAILURE:
982
1062
    
983
 
    fprintf(stderr, "(Avahi browser) %s\n",
984
 
            avahi_strerror(avahi_server_errno(mc.server)));
 
1063
    fprintf_plus(stderr, "(Avahi browser) %s\n",
 
1064
                 avahi_strerror(avahi_server_errno(mc.server)));
985
1065
    avahi_simple_poll_quit(mc.simple_poll);
986
1066
    return;
987
1067
    
994
1074
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
995
1075
                                    name, type, domain, protocol, 0,
996
1076
                                    resolve_callback, NULL) == NULL)
997
 
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
998
 
              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)));
999
1080
    break;
1000
1081
    
1001
1082
  case AVAHI_BROWSER_REMOVE:
1004
1085
  case AVAHI_BROWSER_ALL_FOR_NOW:
1005
1086
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1006
1087
    if(debug){
1007
 
      fprintf(stderr, "No Mandos server found, still searching...\n");
 
1088
      fprintf_plus(stderr, "No Mandos server found, still"
 
1089
                   " searching...\n");
1008
1090
    }
1009
1091
    break;
1010
1092
  }
1011
1093
}
1012
1094
 
1013
 
/* stop main loop after sigterm has been called */
 
1095
/* Signal handler that stops main loop after SIGTERM */
1014
1096
static void handle_sigterm(int sig){
1015
1097
  if(quit_now){
1016
1098
    return;
1018
1100
  quit_now = 1;
1019
1101
  signal_received = sig;
1020
1102
  int old_errno = errno;
 
1103
  /* set main loop to exit */
1021
1104
  if(mc.simple_poll != NULL){
1022
1105
    avahi_simple_poll_quit(mc.simple_poll);
1023
1106
  }
1024
1107
  errno = old_errno;
1025
1108
}
1026
1109
 
1027
 
/* 
1028
 
 * This function determines if a directory entry in /sys/class/net
1029
 
 * corresponds to an acceptable network device.
1030
 
 * (This function is passed to scandir(3) as a filter function.)
1031
 
 */
1032
 
int good_interface(const struct dirent *if_entry){
1033
 
  ssize_t ssret;
1034
 
  char *flagname = NULL;
1035
 
  int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net,
1036
 
                     if_entry->d_name);
1037
 
  if(ret < 0){
1038
 
    perror("asprintf");
1039
 
    return 0;
1040
 
  }
1041
 
  if(if_entry->d_name[0] == '.'){
1042
 
    return 0;
1043
 
  }
1044
 
  int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY));
1045
 
  if(flags_fd == -1){
1046
 
    perror("open");
1047
 
    return 0;
1048
 
  }
1049
 
  typedef short ifreq_flags;    /* ifreq.ifr_flags in netdevice(7) */
1050
 
  /* read line from flags_fd */
1051
 
  ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */
1052
 
  char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */
1053
 
  flagstring[(size_t)to_read] = '\0';
1054
 
  if(flagstring == NULL){
1055
 
    perror("malloc");
1056
 
    close(flags_fd);
1057
 
    return 0;
1058
 
  }
1059
 
  while(to_read > 0){
1060
 
    ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring,
1061
 
                                             (size_t)to_read));
1062
 
    if(ssret == -1){
1063
 
      perror("read");
1064
 
      free(flagstring);
1065
 
      close(flags_fd);
1066
 
      return 0;
1067
 
    }
1068
 
    to_read -= ssret;
1069
 
    if(ssret == 0){
1070
 
      break;
1071
 
    }
1072
 
  }
1073
 
  close(flags_fd);
1074
 
  intmax_t tmpmax;
1075
 
  char *tmp;
1076
 
  errno = 0;
1077
 
  tmpmax = strtoimax(flagstring, &tmp, 0);
1078
 
  if(errno != 0 or tmp == flagstring or (*tmp != '\0'
1079
 
                                         and not (isspace(*tmp)))
1080
 
     or tmpmax != (ifreq_flags)tmpmax){
 
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){
1081
1121
    if(debug){
1082
 
      fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n",
1083
 
              flagstring, if_entry->d_name);
 
1122
      perror_plus("ioctl SIOCGIFFLAGS");
1084
1123
    }
1085
 
    free(flagstring);
1086
 
    return 0;
 
1124
    return false;
1087
1125
  }
1088
 
  free(flagstring);
1089
 
  ifreq_flags flags = (ifreq_flags)tmpmax;
 
1126
  return true;
 
1127
}
 
1128
 
 
1129
bool good_flags(const char *ifname, const struct ifreq *ifr){
 
1130
  
1090
1131
  /* Reject the loopback device */
1091
 
  if(flags & IFF_LOOPBACK){
 
1132
  if(ifr->ifr_flags & IFF_LOOPBACK){
1092
1133
    if(debug){
1093
 
      fprintf(stderr, "Rejecting loopback interface \"%s\"\n",
1094
 
              if_entry->d_name);
 
1134
      fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n",
 
1135
                   ifname);
1095
1136
    }
1096
 
    return 0;
 
1137
    return false;
1097
1138
  }
1098
1139
  /* Accept point-to-point devices only if connect_to is specified */
1099
 
  if(connect_to != NULL and (flags & IFF_POINTOPOINT)){
 
1140
  if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){
1100
1141
    if(debug){
1101
 
      fprintf(stderr, "Accepting point-to-point interface \"%s\"\n",
1102
 
              if_entry->d_name);
 
1142
      fprintf_plus(stderr, "Accepting point-to-point interface"
 
1143
                   " \"%s\"\n", ifname);
1103
1144
    }
1104
 
    return 1;
 
1145
    return true;
1105
1146
  }
1106
1147
  /* Otherwise, reject non-broadcast-capable devices */
1107
 
  if(not (flags & IFF_BROADCAST)){
1108
 
    if(debug){
1109
 
      fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n",
1110
 
              if_entry->d_name);
1111
 
    }
1112
 
    return 0;
1113
 
  }
 
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
  
1114
1164
  /* Accept this device */
1115
1165
  if(debug){
1116
 
    fprintf(stderr, "Interface \"%s\" is acceptable\n",
1117
 
            if_entry->d_name);
1118
 
  }
1119
 
  return 1;
 
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;
1120
1475
}
1121
1476
 
1122
1477
int main(int argc, char *argv[]){
1141
1496
  bool gnutls_initialized = false;
1142
1497
  bool gpgme_initialized = false;
1143
1498
  float delay = 2.5f;
 
1499
  double retry_interval = 10; /* 10s between trying a server and
 
1500
                                 retrying the same server again */
1144
1501
  
1145
1502
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1146
1503
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1152
1509
  errno = 0;
1153
1510
  ret = setgid(gid);
1154
1511
  if(ret == -1){
1155
 
    perror("setgid");
 
1512
    perror_plus("setgid");
1156
1513
  }
1157
1514
  
1158
1515
  /* Lower user privileges (temporarily) */
1159
1516
  errno = 0;
1160
1517
  ret = seteuid(uid);
1161
1518
  if(ret == -1){
1162
 
    perror("seteuid");
 
1519
    perror_plus("seteuid");
1163
1520
  }
1164
1521
  
1165
1522
  if(quit_now){
1200
1557
        .arg = "SECONDS",
1201
1558
        .doc = "Maximum delay to wait for interface startup",
1202
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 },
1203
1568
      /*
1204
1569
       * These reproduce what we would get without ARGP_NO_HELP
1205
1570
       */
1249
1614
        if(errno != 0 or tmp == arg or *tmp != '\0'){
1250
1615
          argp_error(state, "Bad delay");
1251
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;
1252
1628
        break;
1253
1629
        /*
1254
1630
         * These reproduce what we would get without ARGP_NO_HELP
1261
1637
        argp_state_help(state, state->out_stream,
1262
1638
                        ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR);
1263
1639
      case 'V':                 /* --version */
1264
 
        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);
1265
1643
        exit(argp_err_exit_status);
1266
1644
        break;
1267
1645
      default:
1282
1660
    case ENOMEM:
1283
1661
    default:
1284
1662
      errno = ret;
1285
 
      perror("argp_parse");
 
1663
      perror_plus("argp_parse");
1286
1664
      exitcode = EX_OSERR;
1287
1665
      goto end;
1288
1666
    case EINVAL:
1290
1668
      goto end;
1291
1669
    }
1292
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
  }
1293
1752
  
1294
1753
  if(not debug){
1295
1754
    avahi_set_log_function(empty_log);
1296
1755
  }
1297
 
 
 
1756
  
1298
1757
  if(interface[0] == '\0'){
1299
1758
    struct dirent **direntries;
1300
 
    ret = scandir(sys_class_net, &direntries, good_interface,
 
1759
    /* First look for interfaces that are up */
 
1760
    ret = scandir(sys_class_net, &direntries, up_interface,
1301
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
    }
1302
1768
    if(ret >= 1){
1303
 
      /* Pick the first good interface */
 
1769
      /* Pick the first interface returned */
1304
1770
      interface = strdup(direntries[0]->d_name);
1305
1771
      if(debug){
1306
 
        fprintf(stderr, "Using interface \"%s\"\n", interface);
 
1772
        fprintf_plus(stderr, "Using interface \"%s\"\n", interface);
1307
1773
      }
1308
1774
      if(interface == NULL){
1309
 
        perror("malloc");
 
1775
        perror_plus("malloc");
1310
1776
        free(direntries);
1311
1777
        exitcode = EXIT_FAILURE;
1312
1778
        goto end;
1314
1780
      free(direntries);
1315
1781
    } else {
1316
1782
      free(direntries);
1317
 
      fprintf(stderr, "Could not find a network interface\n");
 
1783
      fprintf_plus(stderr, "Could not find a network interface\n");
1318
1784
      exitcode = EXIT_FAILURE;
1319
1785
      goto end;
1320
1786
    }
1326
1792
  srand((unsigned int) time(NULL));
1327
1793
  mc.simple_poll = avahi_simple_poll_new();
1328
1794
  if(mc.simple_poll == NULL){
1329
 
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1795
    fprintf_plus(stderr,
 
1796
                 "Avahi: Failed to create simple poll object.\n");
1330
1797
    exitcode = EX_UNAVAILABLE;
1331
1798
    goto end;
1332
1799
  }
1334
1801
  sigemptyset(&sigterm_action.sa_mask);
1335
1802
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1336
1803
  if(ret == -1){
1337
 
    perror("sigaddset");
 
1804
    perror_plus("sigaddset");
1338
1805
    exitcode = EX_OSERR;
1339
1806
    goto end;
1340
1807
  }
1341
1808
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1342
1809
  if(ret == -1){
1343
 
    perror("sigaddset");
 
1810
    perror_plus("sigaddset");
1344
1811
    exitcode = EX_OSERR;
1345
1812
    goto end;
1346
1813
  }
1347
1814
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1348
1815
  if(ret == -1){
1349
 
    perror("sigaddset");
 
1816
    perror_plus("sigaddset");
1350
1817
    exitcode = EX_OSERR;
1351
1818
    goto end;
1352
1819
  }
1356
1823
  */
1357
1824
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1358
1825
  if(ret == -1){
1359
 
    perror("sigaction");
 
1826
    perror_plus("sigaction");
1360
1827
    return EX_OSERR;
1361
1828
  }
1362
1829
  if(old_sigterm_action.sa_handler != SIG_IGN){
1363
1830
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1364
1831
    if(ret == -1){
1365
 
      perror("sigaction");
 
1832
      perror_plus("sigaction");
1366
1833
      exitcode = EX_OSERR;
1367
1834
      goto end;
1368
1835
    }
1369
1836
  }
1370
1837
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1371
1838
  if(ret == -1){
1372
 
    perror("sigaction");
 
1839
    perror_plus("sigaction");
1373
1840
    return EX_OSERR;
1374
1841
  }
1375
1842
  if(old_sigterm_action.sa_handler != SIG_IGN){
1376
1843
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1377
1844
    if(ret == -1){
1378
 
      perror("sigaction");
 
1845
      perror_plus("sigaction");
1379
1846
      exitcode = EX_OSERR;
1380
1847
      goto end;
1381
1848
    }
1382
1849
  }
1383
1850
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1384
1851
  if(ret == -1){
1385
 
    perror("sigaction");
 
1852
    perror_plus("sigaction");
1386
1853
    return EX_OSERR;
1387
1854
  }
1388
1855
  if(old_sigterm_action.sa_handler != SIG_IGN){
1389
1856
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1390
1857
    if(ret == -1){
1391
 
      perror("sigaction");
 
1858
      perror_plus("sigaction");
1392
1859
      exitcode = EX_OSERR;
1393
1860
      goto end;
1394
1861
    }
1398
1865
  if(strcmp(interface, "none") != 0){
1399
1866
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1400
1867
    if(if_index == 0){
1401
 
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1868
      fprintf_plus(stderr, "No such interface: \"%s\"\n", interface);
1402
1869
      exitcode = EX_UNAVAILABLE;
1403
1870
      goto end;
1404
1871
    }
1411
1878
    errno = 0;
1412
1879
    ret = seteuid(0);
1413
1880
    if(ret == -1){
1414
 
      perror("seteuid");
 
1881
      perror_plus("seteuid");
1415
1882
    }
1416
1883
    
1417
1884
#ifdef __linux__
1421
1888
    bool restore_loglevel = true;
1422
1889
    if(ret == -1){
1423
1890
      restore_loglevel = false;
1424
 
      perror("klogctl");
 
1891
      perror_plus("klogctl");
1425
1892
    }
1426
1893
#endif  /* __linux__ */
1427
1894
    
1428
1895
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1429
1896
    if(sd < 0){
1430
 
      perror("socket");
 
1897
      perror_plus("socket");
1431
1898
      exitcode = EX_OSERR;
1432
1899
#ifdef __linux__
1433
1900
      if(restore_loglevel){
1434
1901
        ret = klogctl(7, NULL, 0);
1435
1902
        if(ret == -1){
1436
 
          perror("klogctl");
 
1903
          perror_plus("klogctl");
1437
1904
        }
1438
1905
      }
1439
1906
#endif  /* __linux__ */
1441
1908
      errno = 0;
1442
1909
      ret = seteuid(uid);
1443
1910
      if(ret == -1){
1444
 
        perror("seteuid");
 
1911
        perror_plus("seteuid");
1445
1912
      }
1446
1913
      goto end;
1447
1914
    }
1448
1915
    strcpy(network.ifr_name, interface);
1449
1916
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1450
1917
    if(ret == -1){
1451
 
      perror("ioctl SIOCGIFFLAGS");
 
1918
      perror_plus("ioctl SIOCGIFFLAGS");
1452
1919
#ifdef __linux__
1453
1920
      if(restore_loglevel){
1454
1921
        ret = klogctl(7, NULL, 0);
1455
1922
        if(ret == -1){
1456
 
          perror("klogctl");
 
1923
          perror_plus("klogctl");
1457
1924
        }
1458
1925
      }
1459
1926
#endif  /* __linux__ */
1462
1929
      errno = 0;
1463
1930
      ret = seteuid(uid);
1464
1931
      if(ret == -1){
1465
 
        perror("seteuid");
 
1932
        perror_plus("seteuid");
1466
1933
      }
1467
1934
      goto end;
1468
1935
    }
1472
1939
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1473
1940
      if(ret == -1){
1474
1941
        take_down_interface = false;
1475
 
        perror("ioctl SIOCSIFFLAGS +IFF_UP");
 
1942
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1476
1943
        exitcode = EX_OSERR;
1477
1944
#ifdef __linux__
1478
1945
        if(restore_loglevel){
1479
1946
          ret = klogctl(7, NULL, 0);
1480
1947
          if(ret == -1){
1481
 
            perror("klogctl");
 
1948
            perror_plus("klogctl");
1482
1949
          }
1483
1950
        }
1484
1951
#endif  /* __linux__ */
1486
1953
        errno = 0;
1487
1954
        ret = seteuid(uid);
1488
1955
        if(ret == -1){
1489
 
          perror("seteuid");
 
1956
          perror_plus("seteuid");
1490
1957
        }
1491
1958
        goto end;
1492
1959
      }
1493
1960
    }
1494
 
    /* sleep checking until interface is running */
 
1961
    /* Sleep checking until interface is running.
 
1962
       Check every 0.25s, up to total time of delay */
1495
1963
    for(int i=0; i < delay * 4; i++){
1496
1964
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1497
1965
      if(ret == -1){
1498
 
        perror("ioctl SIOCGIFFLAGS");
 
1966
        perror_plus("ioctl SIOCGIFFLAGS");
1499
1967
      } else if(network.ifr_flags & IFF_RUNNING){
1500
1968
        break;
1501
1969
      }
1502
1970
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1503
1971
      ret = nanosleep(&sleeptime, NULL);
1504
1972
      if(ret == -1 and errno != EINTR){
1505
 
        perror("nanosleep");
 
1973
        perror_plus("nanosleep");
1506
1974
      }
1507
1975
    }
1508
1976
    if(not take_down_interface){
1509
1977
      /* We won't need the socket anymore */
1510
1978
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1511
1979
      if(ret == -1){
1512
 
        perror("close");
 
1980
        perror_plus("close");
1513
1981
      }
1514
1982
    }
1515
1983
#ifdef __linux__
1517
1985
      /* Restores kernel loglevel to default */
1518
1986
      ret = klogctl(7, NULL, 0);
1519
1987
      if(ret == -1){
1520
 
        perror("klogctl");
 
1988
        perror_plus("klogctl");
1521
1989
      }
1522
1990
    }
1523
1991
#endif  /* __linux__ */
1524
1992
    /* Lower privileges */
1525
1993
    errno = 0;
1526
 
    if(take_down_interface){
1527
 
      /* Lower privileges */
1528
 
      ret = seteuid(uid);
1529
 
      if(ret == -1){
1530
 
        perror("seteuid");
1531
 
      }
1532
 
    } else {
1533
 
      /* Lower privileges permanently */
1534
 
      ret = setuid(uid);
1535
 
      if(ret == -1){
1536
 
        perror("setuid");
1537
 
      }
 
1994
    /* Lower privileges */
 
1995
    ret = seteuid(uid);
 
1996
    if(ret == -1){
 
1997
      perror_plus("seteuid");
1538
1998
    }
1539
1999
  }
1540
2000
  
1544
2004
  
1545
2005
  ret = init_gnutls_global(pubkey, seckey);
1546
2006
  if(ret == -1){
1547
 
    fprintf(stderr, "init_gnutls_global failed\n");
 
2007
    fprintf_plus(stderr, "init_gnutls_global failed\n");
1548
2008
    exitcode = EX_UNAVAILABLE;
1549
2009
    goto end;
1550
2010
  } else {
1555
2015
    goto end;
1556
2016
  }
1557
2017
  
 
2018
  if(mkdtemp(tempdir) == NULL){
 
2019
    perror_plus("mkdtemp");
 
2020
    goto end;
 
2021
  }
1558
2022
  tempdir_created = true;
1559
 
  if(mkdtemp(tempdir) == NULL){
1560
 
    tempdir_created = false;
1561
 
    perror("mkdtemp");
1562
 
    goto end;
1563
 
  }
1564
2023
  
1565
2024
  if(quit_now){
1566
2025
    goto end;
1567
2026
  }
1568
2027
  
1569
2028
  if(not init_gpgme(pubkey, seckey, tempdir)){
1570
 
    fprintf(stderr, "init_gpgme failed\n");
 
2029
    fprintf_plus(stderr, "init_gpgme failed\n");
1571
2030
    exitcode = EX_UNAVAILABLE;
1572
2031
    goto end;
1573
2032
  } else {
1583
2042
    /* (Mainly meant for debugging) */
1584
2043
    char *address = strrchr(connect_to, ':');
1585
2044
    if(address == NULL){
1586
 
      fprintf(stderr, "No colon in address\n");
 
2045
      fprintf_plus(stderr, "No colon in address\n");
1587
2046
      exitcode = EX_USAGE;
1588
2047
      goto end;
1589
2048
    }
1597
2056
    tmpmax = strtoimax(address+1, &tmp, 10);
1598
2057
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
1599
2058
       or tmpmax != (uint16_t)tmpmax){
1600
 
      fprintf(stderr, "Bad port number\n");
 
2059
      fprintf_plus(stderr, "Bad port number\n");
1601
2060
      exitcode = EX_USAGE;
1602
2061
      goto end;
1603
2062
    }
1608
2067
    
1609
2068
    port = (uint16_t)tmpmax;
1610
2069
    *address = '\0';
1611
 
    address = connect_to;
1612
2070
    /* Colon in address indicates IPv6 */
1613
2071
    int af;
1614
 
    if(strchr(address, ':') != NULL){
 
2072
    if(strchr(connect_to, ':') != NULL){
1615
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
        }
1616
2080
    } else {
1617
2081
      af = AF_INET;
1618
2082
    }
 
2083
    address = connect_to;
1619
2084
    
1620
2085
    if(quit_now){
1621
2086
      goto end;
1622
2087
    }
1623
 
 
 
2088
    
1624
2089
    while(not quit_now){
1625
2090
      ret = start_mandos_communication(address, port, if_index, af);
1626
2091
      if(quit_now or ret == 0){
1627
2092
        break;
1628
2093
      }
1629
 
      sleep(15);
1630
 
    };
1631
 
 
 
2094
      if(debug){
 
2095
        fprintf_plus(stderr, "Retrying in %d seconds\n",
 
2096
                     (int)retry_interval);
 
2097
      }
 
2098
      sleep((int)retry_interval);
 
2099
    }
 
2100
    
1632
2101
    if (not quit_now){
1633
2102
      exitcode = EXIT_SUCCESS;
1634
2103
    }
1635
 
 
 
2104
    
1636
2105
    goto end;
1637
2106
  }
1638
2107
  
1660
2129
  
1661
2130
  /* Check if creating the Avahi server object succeeded */
1662
2131
  if(mc.server == NULL){
1663
 
    fprintf(stderr, "Failed to create Avahi server: %s\n",
1664
 
            avahi_strerror(error));
 
2132
    fprintf_plus(stderr, "Failed to create Avahi server: %s\n",
 
2133
                 avahi_strerror(error));
1665
2134
    exitcode = EX_UNAVAILABLE;
1666
2135
    goto end;
1667
2136
  }
1675
2144
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
1676
2145
                                   NULL, 0, browse_callback, NULL);
1677
2146
  if(sb == NULL){
1678
 
    fprintf(stderr, "Failed to create service browser: %s\n",
1679
 
            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)));
1680
2149
    exitcode = EX_UNAVAILABLE;
1681
2150
    goto end;
1682
2151
  }
1688
2157
  /* Run the main loop */
1689
2158
  
1690
2159
  if(debug){
1691
 
    fprintf(stderr, "Starting Avahi loop search\n");
1692
 
  }
1693
 
  
1694
 
  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
  }
1695
2169
  
1696
2170
 end:
1697
2171
  
1698
2172
  if(debug){
1699
 
    fprintf(stderr, "%s exiting\n", argv[0]);
 
2173
    fprintf_plus(stderr, "%s exiting\n", argv[0]);
1700
2174
  }
1701
2175
  
1702
2176
  /* Cleanup things */
1718
2192
  if(gpgme_initialized){
1719
2193
    gpgme_release(mc.ctx);
1720
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
  }
1721
2206
  
1722
 
  /* Take down the network interface */
1723
 
  if(take_down_interface){
1724
 
    /* Re-raise priviliges */
 
2207
  /* Re-raise priviliges */
 
2208
  {
1725
2209
    errno = 0;
1726
2210
    ret = seteuid(0);
1727
2211
    if(ret == -1){
1728
 
      perror("seteuid");
1729
 
    }
1730
 
    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){
1731
2221
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1732
2222
      if(ret == -1){
1733
 
        perror("ioctl SIOCGIFFLAGS");
1734
 
      } else if(network.ifr_flags & IFF_UP) {
 
2223
        perror_plus("ioctl SIOCGIFFLAGS");
 
2224
      } else if(network.ifr_flags & IFF_UP){
1735
2225
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
1736
2226
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
1737
2227
        if(ret == -1){
1738
 
          perror("ioctl SIOCSIFFLAGS -IFF_UP");
 
2228
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
1739
2229
        }
1740
2230
      }
1741
2231
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1742
2232
      if(ret == -1){
1743
 
        perror("close");
1744
 
      }
1745
 
      /* Lower privileges permanently */
1746
 
      errno = 0;
1747
 
      ret = setuid(uid);
1748
 
      if(ret == -1){
1749
 
        perror("setuid");
 
2233
        perror_plus("close");
1750
2234
      }
1751
2235
    }
1752
2236
  }
 
2237
  /* Lower privileges permanently */
 
2238
  errno = 0;
 
2239
  ret = setuid(uid);
 
2240
  if(ret == -1){
 
2241
    perror_plus("setuid");
 
2242
  }
1753
2243
  
1754
 
  /* Removes the temp directory used by GPGME */
 
2244
  /* Removes the GPGME temp directory and all files inside */
1755
2245
  if(tempdir_created){
1756
 
    DIR *d;
1757
 
    struct dirent *direntry;
1758
 
    d = opendir(tempdir);
1759
 
    if(d == NULL){
1760
 
      if(errno != ENOENT){
1761
 
        perror("opendir");
1762
 
      }
1763
 
    } else {
1764
 
      while(true){
1765
 
        direntry = readdir(d);
1766
 
        if(direntry == NULL){
1767
 
          break;
1768
 
        }
1769
 
        /* Skip "." and ".." */
1770
 
        if(direntry->d_name[0] == '.'
1771
 
           and (direntry->d_name[1] == '\0'
1772
 
                or (direntry->d_name[1] == '.'
1773
 
                    and direntry->d_name[2] == '\0'))){
1774
 
          continue;
1775
 
        }
 
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];
1776
2253
        char *fullname = NULL;
1777
2254
        ret = asprintf(&fullname, "%s/%s", tempdir,
1778
2255
                       direntry->d_name);
1779
2256
        if(ret < 0){
1780
 
          perror("asprintf");
 
2257
          perror_plus("asprintf");
1781
2258
          continue;
1782
2259
        }
1783
2260
        ret = remove(fullname);
1784
2261
        if(ret == -1){
1785
 
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
1786
 
                  strerror(errno));
 
2262
          fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname,
 
2263
                       strerror(errno));
1787
2264
        }
1788
2265
        free(fullname);
1789
2266
      }
1790
 
      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");
1791
2273
    }
1792
2274
    ret = rmdir(tempdir);
1793
2275
    if(ret == -1 and errno != ENOENT){
1794
 
      perror("rmdir");
 
2276
      perror_plus("rmdir");
1795
2277
    }
1796
2278
  }
1797
2279
  
1802
2284
                                            &old_sigterm_action,
1803
2285
                                            NULL));
1804
2286
    if(ret == -1){
1805
 
      perror("sigaction");
 
2287
      perror_plus("sigaction");
1806
2288
    }
1807
2289
    do {
1808
2290
      ret = raise(signal_received);
1809
2291
    } while(ret != 0 and errno == EINTR);
1810
2292
    if(ret != 0){
1811
 
      perror("raise");
 
2293
      perror_plus("raise");
1812
2294
      abort();
1813
2295
    }
1814
2296
    TEMP_FAILURE_RETRY(pause());