/mandos/release

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

« back to all changes in this revision

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

* plugins.d/mandos-client.c: Some white space fixes.
  (runnable_hook): Simplify name rule.  More debug messages.

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