/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

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