/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

added documentation todo

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-2011 Teddy Hogeborn
13
 
 * Copyright © 2008-2011 Björn Påhlsson
 
12
 * Copyright © 2008,2009 Teddy Hogeborn
 
13
 * Copyright © 2008,2009 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@recompile.se>.
 
29
 * Contact the authors at <mandos@fukt.bsnet.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, srand(),
47
 
                                   strtof(), abort() */
 
46
#include <stdlib.h>             /* free(), EXIT_SUCCESS, EXIT_FAILURE,
 
47
                                   srand(), 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(), S_ISREG */
 
56
#include <sys/stat.h>           /* open() */
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
 
                                   program_invocation_short_name */
67
 
#include <time.h>               /* nanosleep(), time(), sleep() */
 
65
#include <errno.h>              /* perror(), errno */
 
66
#include <time.h>               /* nanosleep(), time() */
68
67
#include <net/if.h>             /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP,
69
68
                                   SIOCSIFFLAGS, if_indextoname(),
70
69
                                   if_nametoindex(), IF_NAMESIZE */
74
73
#include <unistd.h>             /* close(), SEEK_SET, off_t, write(),
75
74
                                   getuid(), getgid(), seteuid(),
76
75
                                   setgid(), pause() */
77
 
#include <arpa/inet.h>          /* inet_pton(), htons, inet_ntop() */
 
76
#include <arpa/inet.h>          /* inet_pton(), htons */
78
77
#include <iso646.h>             /* not, or, and */
79
78
#include <argp.h>               /* struct argp_option, error_t, struct
80
79
                                   argp_state, struct argp,
83
82
#include <signal.h>             /* sigemptyset(), sigaddset(),
84
83
                                   sigaction(), SIGTERM, sig_atomic_t,
85
84
                                   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() */
90
85
 
91
86
#ifdef __linux__
92
87
#include <sys/klog.h>           /* klogctl() */
110
105
                                   init_gnutls_session(),
111
106
                                   GNUTLS_* */
112
107
#include <gnutls/openpgp.h>
113
 
                         /* gnutls_certificate_set_openpgp_key_file(),
114
 
                            GNUTLS_OPENPGP_FMT_BASE64 */
 
108
                          /* gnutls_certificate_set_openpgp_key_file(),
 
109
                                   GNUTLS_OPENPGP_FMT_BASE64 */
115
110
 
116
111
/* GPGME */
117
112
#include <gpgme.h>              /* All GPGME types, constants and
125
120
#define PATHDIR "/conf/conf.d/mandos"
126
121
#define SECKEY "seckey.txt"
127
122
#define PUBKEY "pubkey.txt"
128
 
#define HOOKDIR "/lib/mandos/network-hooks.d"
129
123
 
130
124
bool debug = false;
131
125
static const char mandos_protocol_version[] = "1";
132
126
const char *argp_program_version = "mandos-client " VERSION;
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;
 
127
const char *argp_program_bug_address = "<mandos@fukt.bsnet.se>";
148
128
 
149
129
/* Used for passing in values through the Avahi callback functions */
150
130
typedef struct {
155
135
  gnutls_dh_params_t dh_params;
156
136
  const char *priority;
157
137
  gpgme_ctx_t ctx;
158
 
  server *current_server;
159
138
} mandos_context;
160
139
 
161
140
/* global context so signal handler can reach it*/
162
141
mandos_context mc = { .simple_poll = NULL, .server = NULL,
163
142
                      .dh_bits = 1024, .priority = "SECURE256"
164
 
                      ":!CTYPE-X.509:+CTYPE-OPENPGP",
165
 
                      .current_server = NULL };
 
143
                      ":!CTYPE-X.509:+CTYPE-OPENPGP" };
166
144
 
167
145
sig_atomic_t quit_now = 0;
168
146
int signal_received = 0;
169
147
 
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
148
/*
178
149
 * Make additional room in "buffer" for at least BUFFER_SIZE more
179
150
 * bytes. "buffer_capacity" is how much is currently allocated,
180
151
 * "buffer_length" is how much is already used.
181
152
 */
182
153
size_t incbuffer(char **buffer, size_t buffer_length,
183
 
                 size_t buffer_capacity){
 
154
                  size_t buffer_capacity){
184
155
  if(buffer_length + BUFFER_SIZE > buffer_capacity){
185
156
    *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE);
186
157
    if(buffer == NULL){
191
162
  return buffer_capacity;
192
163
}
193
164
 
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
 
 
231
165
/* 
232
166
 * Initialize GPGME.
233
167
 */
234
 
static bool init_gpgme(const char *seckey, const char *pubkey,
235
 
                       const char *tempdir){
 
168
static bool init_gpgme(const char *seckey,
 
169
                       const char *pubkey, const char *tempdir){
236
170
  gpgme_error_t rc;
237
171
  gpgme_engine_info_t engine_info;
238
172
  
247
181
    
248
182
    fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY));
249
183
    if(fd == -1){
250
 
      perror_plus("open");
 
184
      perror("open");
251
185
      return false;
252
186
    }
253
187
    
254
188
    rc = gpgme_data_new_from_fd(&pgp_data, fd);
255
189
    if(rc != GPG_ERR_NO_ERROR){
256
 
      fprintf(stderr, "Mandos plugin mandos-client: "
257
 
              "bad gpgme_data_new_from_fd: %s: %s\n",
 
190
      fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n",
258
191
              gpgme_strsource(rc), gpgme_strerror(rc));
259
192
      return false;
260
193
    }
261
194
    
262
195
    rc = gpgme_op_import(mc.ctx, pgp_data);
263
196
    if(rc != GPG_ERR_NO_ERROR){
264
 
      fprintf(stderr, "Mandos plugin mandos-client: "
265
 
              "bad gpgme_op_import: %s: %s\n",
 
197
      fprintf(stderr, "bad gpgme_op_import: %s: %s\n",
266
198
              gpgme_strsource(rc), gpgme_strerror(rc));
267
199
      return false;
268
200
    }
269
201
    
270
202
    ret = (int)TEMP_FAILURE_RETRY(close(fd));
271
203
    if(ret == -1){
272
 
      perror_plus("close");
 
204
      perror("close");
273
205
    }
274
206
    gpgme_data_release(pgp_data);
275
207
    return true;
276
208
  }
277
209
  
278
210
  if(debug){
279
 
    fprintf(stderr, "Mandos plugin mandos-client: "
280
 
            "Initializing GPGME\n");
 
211
    fprintf(stderr, "Initializing GPGME\n");
281
212
  }
282
213
  
283
214
  /* Init GPGME */
284
215
  gpgme_check_version(NULL);
285
216
  rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP);
286
217
  if(rc != GPG_ERR_NO_ERROR){
287
 
    fprintf(stderr, "Mandos plugin mandos-client: "
288
 
            "bad gpgme_engine_check_version: %s: %s\n",
 
218
    fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n",
289
219
            gpgme_strsource(rc), gpgme_strerror(rc));
290
220
    return false;
291
221
  }
292
222
  
293
 
  /* Set GPGME home directory for the OpenPGP engine only */
 
223
    /* Set GPGME home directory for the OpenPGP engine only */
294
224
  rc = gpgme_get_engine_info(&engine_info);
295
225
  if(rc != GPG_ERR_NO_ERROR){
296
 
    fprintf(stderr, "Mandos plugin mandos-client: "
297
 
            "bad gpgme_get_engine_info: %s: %s\n",
 
226
    fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n",
298
227
            gpgme_strsource(rc), gpgme_strerror(rc));
299
228
    return false;
300
229
  }
307
236
    engine_info = engine_info->next;
308
237
  }
309
238
  if(engine_info == NULL){
310
 
    fprintf(stderr, "Mandos plugin mandos-client: "
311
 
            "Could not set GPGME home dir to %s\n", tempdir);
 
239
    fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir);
312
240
    return false;
313
241
  }
314
242
  
315
243
  /* Create new GPGME "context" */
316
244
  rc = gpgme_new(&(mc.ctx));
317
245
  if(rc != GPG_ERR_NO_ERROR){
318
 
    fprintf(stderr, "Mandos plugin mandos-client: "
319
 
            "bad gpgme_new: %s: %s\n", gpgme_strsource(rc),
320
 
            gpgme_strerror(rc));
 
246
    fprintf(stderr, "bad gpgme_new: %s: %s\n",
 
247
            gpgme_strsource(rc), gpgme_strerror(rc));
321
248
    return false;
322
249
  }
323
250
  
342
269
  ssize_t plaintext_length = 0;
343
270
  
344
271
  if(debug){
345
 
    fprintf(stderr, "Mandos plugin mandos-client: "
346
 
            "Trying to decrypt OpenPGP data\n");
 
272
    fprintf(stderr, "Trying to decrypt OpenPGP data\n");
347
273
  }
348
274
  
349
275
  /* Create new GPGME data buffer from memory cryptotext */
350
276
  rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size,
351
277
                               0);
352
278
  if(rc != GPG_ERR_NO_ERROR){
353
 
    fprintf(stderr, "Mandos plugin mandos-client: "
354
 
            "bad gpgme_data_new_from_mem: %s: %s\n",
 
279
    fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n",
355
280
            gpgme_strsource(rc), gpgme_strerror(rc));
356
281
    return -1;
357
282
  }
359
284
  /* Create new empty GPGME data buffer for the plaintext */
360
285
  rc = gpgme_data_new(&dh_plain);
361
286
  if(rc != GPG_ERR_NO_ERROR){
362
 
    fprintf(stderr, "Mandos plugin mandos-client: "
363
 
            "bad gpgme_data_new: %s: %s\n",
 
287
    fprintf(stderr, "bad gpgme_data_new: %s: %s\n",
364
288
            gpgme_strsource(rc), gpgme_strerror(rc));
365
289
    gpgme_data_release(dh_crypto);
366
290
    return -1;
370
294
     data buffer */
371
295
  rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain);
372
296
  if(rc != GPG_ERR_NO_ERROR){
373
 
    fprintf(stderr, "Mandos plugin mandos-client: "
374
 
            "bad gpgme_op_decrypt: %s: %s\n",
 
297
    fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n",
375
298
            gpgme_strsource(rc), gpgme_strerror(rc));
376
299
    plaintext_length = -1;
377
300
    if(debug){
378
301
      gpgme_decrypt_result_t result;
379
302
      result = gpgme_op_decrypt_result(mc.ctx);
380
303
      if(result == NULL){
381
 
        fprintf(stderr, "Mandos plugin mandos-client: "
382
 
                "gpgme_op_decrypt_result failed\n");
 
304
        fprintf(stderr, "gpgme_op_decrypt_result failed\n");
383
305
      } else {
384
 
        fprintf(stderr, "Mandos plugin mandos-client: "
385
 
                "Unsupported algorithm: %s\n",
 
306
        fprintf(stderr, "Unsupported algorithm: %s\n",
386
307
                result->unsupported_algorithm);
387
 
        fprintf(stderr, "Mandos plugin mandos-client: "
388
 
                "Wrong key usage: %u\n",
 
308
        fprintf(stderr, "Wrong key usage: %u\n",
389
309
                result->wrong_key_usage);
390
310
        if(result->file_name != NULL){
391
 
          fprintf(stderr, "Mandos plugin mandos-client: "
392
 
                  "File name: %s\n", result->file_name);
 
311
          fprintf(stderr, "File name: %s\n", result->file_name);
393
312
        }
394
313
        gpgme_recipient_t recipient;
395
314
        recipient = result->recipients;
396
315
        while(recipient != NULL){
397
 
          fprintf(stderr, "Mandos plugin mandos-client: "
398
 
                  "Public key algorithm: %s\n",
 
316
          fprintf(stderr, "Public key algorithm: %s\n",
399
317
                  gpgme_pubkey_algo_name(recipient->pubkey_algo));
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",
 
318
          fprintf(stderr, "Key ID: %s\n", recipient->keyid);
 
319
          fprintf(stderr, "Secret key available: %s\n",
404
320
                  recipient->status == GPG_ERR_NO_SECKEY
405
321
                  ? "No" : "Yes");
406
322
          recipient = recipient->next;
411
327
  }
412
328
  
413
329
  if(debug){
414
 
    fprintf(stderr, "Mandos plugin mandos-client: "
415
 
            "Decryption of OpenPGP data succeeded\n");
 
330
    fprintf(stderr, "Decryption of OpenPGP data succeeded\n");
416
331
  }
417
332
  
418
333
  /* Seek back to the beginning of the GPGME plaintext data buffer */
419
334
  if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){
420
 
    perror_plus("gpgme_data_seek");
 
335
    perror("gpgme_data_seek");
421
336
    plaintext_length = -1;
422
337
    goto decrypt_end;
423
338
  }
425
340
  *plaintext = NULL;
426
341
  while(true){
427
342
    plaintext_capacity = incbuffer(plaintext,
428
 
                                   (size_t)plaintext_length,
429
 
                                   plaintext_capacity);
 
343
                                      (size_t)plaintext_length,
 
344
                                      plaintext_capacity);
430
345
    if(plaintext_capacity == 0){
431
 
      perror_plus("incbuffer");
432
 
      plaintext_length = -1;
433
 
      goto decrypt_end;
 
346
        perror("incbuffer");
 
347
        plaintext_length = -1;
 
348
        goto decrypt_end;
434
349
    }
435
350
    
436
351
    ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length,
441
356
      break;
442
357
    }
443
358
    if(ret < 0){
444
 
      perror_plus("gpgme_data_read");
 
359
      perror("gpgme_data_read");
445
360
      plaintext_length = -1;
446
361
      goto decrypt_end;
447
362
    }
449
364
  }
450
365
  
451
366
  if(debug){
452
 
    fprintf(stderr, "Mandos plugin mandos-client: "
453
 
            "Decrypted password is: ");
 
367
    fprintf(stderr, "Decrypted password is: ");
454
368
    for(ssize_t i = 0; i < plaintext_length; i++){
455
369
      fprintf(stderr, "%02hhX ", (*plaintext)[i]);
456
370
    }
478
392
/* GnuTLS log function callback */
479
393
static void debuggnutls(__attribute__((unused)) int level,
480
394
                        const char* string){
481
 
  fprintf(stderr, "Mandos plugin mandos-client: GnuTLS: %s", string);
 
395
  fprintf(stderr, "GnuTLS: %s", string);
482
396
}
483
397
 
484
398
static int init_gnutls_global(const char *pubkeyfilename,
486
400
  int ret;
487
401
  
488
402
  if(debug){
489
 
    fprintf(stderr, "Mandos plugin mandos-client: "
490
 
            "Initializing GnuTLS\n");
 
403
    fprintf(stderr, "Initializing GnuTLS\n");
491
404
  }
492
405
  
493
406
  ret = gnutls_global_init();
494
407
  if(ret != GNUTLS_E_SUCCESS){
495
 
    fprintf(stderr, "Mandos plugin mandos-client: "
496
 
            "GnuTLS global_init: %s\n", safer_gnutls_strerror(ret));
 
408
    fprintf(stderr, "GnuTLS global_init: %s\n",
 
409
            safer_gnutls_strerror(ret));
497
410
    return -1;
498
411
  }
499
412
  
506
419
  }
507
420
  
508
421
  /* OpenPGP credentials */
509
 
  ret = gnutls_certificate_allocate_credentials(&mc.cred);
 
422
  gnutls_certificate_allocate_credentials(&mc.cred);
510
423
  if(ret != GNUTLS_E_SUCCESS){
511
 
    fprintf(stderr, "Mandos plugin mandos-client: "
512
 
            "GnuTLS memory error: %s\n", safer_gnutls_strerror(ret));
 
424
    fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning
 
425
                                                    from
 
426
                                                    -Wunreachable-code
 
427
                                                 */
 
428
            safer_gnutls_strerror(ret));
513
429
    gnutls_global_deinit();
514
430
    return -1;
515
431
  }
516
432
  
517
433
  if(debug){
518
 
    fprintf(stderr, "Mandos plugin mandos-client: "
519
 
            "Attempting to use OpenPGP public key %s and"
 
434
    fprintf(stderr, "Attempting to use OpenPGP public key %s and"
520
435
            " secret key %s as GnuTLS credentials\n", pubkeyfilename,
521
436
            seckeyfilename);
522
437
  }
526
441
     GNUTLS_OPENPGP_FMT_BASE64);
527
442
  if(ret != GNUTLS_E_SUCCESS){
528
443
    fprintf(stderr,
529
 
            "Mandos plugin mandos-client: "
530
444
            "Error[%d] while reading the OpenPGP key pair ('%s',"
531
445
            " '%s')\n", ret, pubkeyfilename, seckeyfilename);
532
 
    fprintf(stderr, "Mandos plugin mandos-client: "
533
 
            "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret));
 
446
    fprintf(stderr, "The GnuTLS error is: %s\n",
 
447
            safer_gnutls_strerror(ret));
534
448
    goto globalfail;
535
449
  }
536
450
  
537
451
  /* GnuTLS server initialization */
538
452
  ret = gnutls_dh_params_init(&mc.dh_params);
539
453
  if(ret != GNUTLS_E_SUCCESS){
540
 
    fprintf(stderr, "Mandos plugin mandos-client: "
541
 
            "Error in GnuTLS DH parameter initialization:"
 
454
    fprintf(stderr, "Error in GnuTLS DH parameter initialization:"
542
455
            " %s\n", safer_gnutls_strerror(ret));
543
456
    goto globalfail;
544
457
  }
545
458
  ret = gnutls_dh_params_generate2(mc.dh_params, mc.dh_bits);
546
459
  if(ret != GNUTLS_E_SUCCESS){
547
 
    fprintf(stderr, "Mandos plugin mandos-client: "
548
 
            "Error in GnuTLS prime generation: %s\n",
 
460
    fprintf(stderr, "Error in GnuTLS prime generation: %s\n",
549
461
            safer_gnutls_strerror(ret));
550
462
    goto globalfail;
551
463
  }
572
484
    }
573
485
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
574
486
  if(ret != GNUTLS_E_SUCCESS){
575
 
    fprintf(stderr, "Mandos plugin mandos-client: "
576
 
            "Error in GnuTLS session initialization: %s\n",
 
487
    fprintf(stderr, "Error in GnuTLS session initialization: %s\n",
577
488
            safer_gnutls_strerror(ret));
578
489
  }
579
490
  
587
498
      }
588
499
    } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
589
500
    if(ret != GNUTLS_E_SUCCESS){
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));
 
501
      fprintf(stderr, "Syntax error at: %s\n", err);
 
502
      fprintf(stderr, "GnuTLS error: %s\n",
 
503
              safer_gnutls_strerror(ret));
594
504
      gnutls_deinit(*session);
595
505
      return -1;
596
506
    }
605
515
    }
606
516
  } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN);
607
517
  if(ret != GNUTLS_E_SUCCESS){
608
 
    fprintf(stderr, "Mandos plugin mandos-client: "
609
 
            "Error setting GnuTLS credentials: %s\n",
 
518
    fprintf(stderr, "Error setting GnuTLS credentials: %s\n",
610
519
            safer_gnutls_strerror(ret));
611
520
    gnutls_deinit(*session);
612
521
    return -1;
643
552
  gnutls_session_t session;
644
553
  int pf;                       /* Protocol family */
645
554
  
646
 
  errno = 0;
647
 
  
648
555
  if(quit_now){
649
 
    errno = EINTR;
650
556
    return -1;
651
557
  }
652
558
  
658
564
    pf = PF_INET;
659
565
    break;
660
566
  default:
661
 
    fprintf(stderr, "Mandos plugin mandos-client: "
662
 
            "Bad address family: %d\n", af);
663
 
    errno = EINVAL;
 
567
    fprintf(stderr, "Bad address family: %d\n", af);
664
568
    return -1;
665
569
  }
666
570
  
670
574
  }
671
575
  
672
576
  if(debug){
673
 
    fprintf(stderr, "Mandos plugin mandos-client: "
674
 
            "Setting up a TCP connection to %s, port %" PRIu16
 
577
    fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16
675
578
            "\n", ip, port);
676
579
  }
677
580
  
678
581
  tcp_sd = socket(pf, SOCK_STREAM, 0);
679
582
  if(tcp_sd < 0){
680
 
    int e = errno;
681
 
    perror_plus("socket");
682
 
    errno = e;
 
583
    perror("socket");
683
584
    goto mandos_end;
684
585
  }
685
586
  
686
587
  if(quit_now){
687
 
    errno = EINTR;
688
588
    goto mandos_end;
689
589
  }
690
590
  
697
597
    ret = inet_pton(af, ip, &to.in.sin_addr);
698
598
  }
699
599
  if(ret < 0 ){
700
 
    int e = errno;
701
 
    perror_plus("inet_pton");
702
 
    errno = e;
 
600
    perror("inet_pton");
703
601
    goto mandos_end;
704
602
  }
705
603
  if(ret == 0){
706
 
    int e = errno;
707
 
    fprintf(stderr, "Mandos plugin mandos-client: "
708
 
            "Bad address: %s\n", ip);
709
 
    errno = e;
 
604
    fprintf(stderr, "Bad address: %s\n", ip);
710
605
    goto mandos_end;
711
606
  }
712
607
  if(af == AF_INET6){
716
611
    
717
612
    if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */
718
613
       (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and
719
 
                                -Wunreachable-code*/
 
614
                              -Wunreachable-code*/
720
615
      if(if_index == AVAHI_IF_UNSPEC){
721
 
        fprintf(stderr, "Mandos plugin mandos-client: "
722
 
                "An IPv6 link-local address is incomplete"
 
616
        fprintf(stderr, "An IPv6 link-local address is incomplete"
723
617
                " without a network interface\n");
724
 
        errno = EINVAL;
725
618
        goto mandos_end;
726
619
      }
727
620
      /* Set the network interface number as scope */
734
627
  }
735
628
  
736
629
  if(quit_now){
737
 
    errno = EINTR;
738
630
    goto mandos_end;
739
631
  }
740
632
  
742
634
    if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){
743
635
      char interface[IF_NAMESIZE];
744
636
      if(if_indextoname((unsigned int)if_index, interface) == NULL){
745
 
        perror_plus("if_indextoname");
 
637
        perror("if_indextoname");
746
638
      } else {
747
 
        fprintf(stderr, "Mandos plugin mandos-client: "
748
 
                "Connection to: %s%%%s, port %" PRIu16 "\n",
 
639
        fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n",
749
640
                ip, interface, port);
750
641
      }
751
642
    } else {
752
 
      fprintf(stderr, "Mandos plugin mandos-client: "
753
 
              "Connection to: %s, port %" PRIu16 "\n", ip, port);
 
643
      fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip,
 
644
              port);
754
645
    }
755
646
    char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ?
756
647
                 INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = "";
763
654
                        sizeof(addrstr));
764
655
    }
765
656
    if(pcret == NULL){
766
 
      perror_plus("inet_ntop");
 
657
      perror("inet_ntop");
767
658
    } else {
768
659
      if(strcmp(addrstr, ip) != 0){
769
 
        fprintf(stderr, "Mandos plugin mandos-client: "
770
 
                "Canonical address form: %s\n", addrstr);
 
660
        fprintf(stderr, "Canonical address form: %s\n", addrstr);
771
661
      }
772
662
    }
773
663
  }
774
664
  
775
665
  if(quit_now){
776
 
    errno = EINTR;
777
666
    goto mandos_end;
778
667
  }
779
668
  
783
672
    ret = connect(tcp_sd, &to.in, sizeof(to)); /* IPv4 */
784
673
  }
785
674
  if(ret < 0){
786
 
    if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){
787
 
      int e = errno;
788
 
      perror_plus("connect");
789
 
      errno = e;
790
 
    }
 
675
    perror("connect");
791
676
    goto mandos_end;
792
677
  }
793
678
  
794
679
  if(quit_now){
795
 
    errno = EINTR;
796
680
    goto mandos_end;
797
681
  }
798
682
  
801
685
  while(true){
802
686
    size_t out_size = strlen(out);
803
687
    ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written,
804
 
                                        out_size - written));
 
688
                                   out_size - written));
805
689
    if(ret == -1){
806
 
      int e = errno;
807
 
      perror_plus("write");
808
 
      errno = e;
 
690
      perror("write");
809
691
      goto mandos_end;
810
692
    }
811
693
    written += (size_t)ret;
821
703
    }
822
704
  
823
705
    if(quit_now){
824
 
      errno = EINTR;
825
706
      goto mandos_end;
826
707
    }
827
708
  }
828
709
  
829
710
  if(debug){
830
 
    fprintf(stderr, "Mandos plugin mandos-client: "
831
 
            "Establishing TLS session with %s\n", ip);
 
711
    fprintf(stderr, "Establishing TLS session with %s\n", ip);
832
712
  }
833
713
  
834
714
  if(quit_now){
835
 
    errno = EINTR;
836
715
    goto mandos_end;
837
716
  }
838
717
  
839
 
  /* Spurious warning from -Wint-to-pointer-cast */
840
718
  gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd);
841
719
  
842
720
  if(quit_now){
843
 
    errno = EINTR;
844
721
    goto mandos_end;
845
722
  }
846
723
  
847
724
  do {
848
725
    ret = gnutls_handshake(session);
849
726
    if(quit_now){
850
 
      errno = EINTR;
851
727
      goto mandos_end;
852
728
    }
853
729
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
854
730
  
855
731
  if(ret != GNUTLS_E_SUCCESS){
856
732
    if(debug){
857
 
      fprintf(stderr, "Mandos plugin mandos-client: "
858
 
              "*** GnuTLS Handshake failed ***\n");
 
733
      fprintf(stderr, "*** GnuTLS Handshake failed ***\n");
859
734
      gnutls_perror(ret);
860
735
    }
861
 
    errno = EPROTO;
862
736
    goto mandos_end;
863
737
  }
864
738
  
865
739
  /* Read OpenPGP packet that contains the wanted password */
866
740
  
867
741
  if(debug){
868
 
    fprintf(stderr, "Mandos plugin mandos-client: "
869
 
            "Retrieving OpenPGP encrypted password from %s\n", ip);
 
742
    fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n",
 
743
            ip);
870
744
  }
871
745
  
872
746
  while(true){
873
747
    
874
748
    if(quit_now){
875
 
      errno = EINTR;
876
749
      goto mandos_end;
877
750
    }
878
751
    
879
752
    buffer_capacity = incbuffer(&buffer, buffer_length,
880
 
                                buffer_capacity);
 
753
                                   buffer_capacity);
881
754
    if(buffer_capacity == 0){
882
 
      int e = errno;
883
 
      perror_plus("incbuffer");
884
 
      errno = e;
 
755
      perror("incbuffer");
885
756
      goto mandos_end;
886
757
    }
887
758
    
888
759
    if(quit_now){
889
 
      errno = EINTR;
890
760
      goto mandos_end;
891
761
    }
892
762
    
905
775
          ret = gnutls_handshake(session);
906
776
          
907
777
          if(quit_now){
908
 
            errno = EINTR;
909
778
            goto mandos_end;
910
779
          }
911
780
        } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
912
781
        if(ret < 0){
913
 
          fprintf(stderr, "Mandos plugin mandos-client: "
914
 
                  "*** GnuTLS Re-handshake failed ***\n");
 
782
          fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n");
915
783
          gnutls_perror(ret);
916
 
          errno = EPROTO;
917
784
          goto mandos_end;
918
785
        }
919
786
        break;
920
787
      default:
921
 
        fprintf(stderr, "Mandos plugin mandos-client: "
922
 
                "Unknown error while reading data from"
 
788
        fprintf(stderr, "Unknown error while reading data from"
923
789
                " encrypted session with Mandos server\n");
924
790
        gnutls_bye(session, GNUTLS_SHUT_RDWR);
925
 
        errno = EIO;
926
791
        goto mandos_end;
927
792
      }
928
793
    } else {
931
796
  }
932
797
  
933
798
  if(debug){
934
 
    fprintf(stderr, "Mandos plugin mandos-client: "
935
 
            "Closing TLS session\n");
 
799
    fprintf(stderr, "Closing TLS session\n");
936
800
  }
937
801
  
938
802
  if(quit_now){
939
 
    errno = EINTR;
940
803
    goto mandos_end;
941
804
  }
942
805
  
943
806
  do {
944
807
    ret = gnutls_bye(session, GNUTLS_SHUT_RDWR);
945
808
    if(quit_now){
946
 
      errno = EINTR;
947
809
      goto mandos_end;
948
810
    }
949
811
  } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED);
950
812
  
951
813
  if(buffer_length > 0){
952
814
    ssize_t decrypted_buffer_size;
953
 
    decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length,
 
815
    decrypted_buffer_size = pgp_packet_decrypt(buffer,
 
816
                                               buffer_length,
954
817
                                               &decrypted_buffer);
955
818
    if(decrypted_buffer_size >= 0){
956
819
      
957
820
      written = 0;
958
821
      while(written < (size_t) decrypted_buffer_size){
959
822
        if(quit_now){
960
 
          errno = EINTR;
961
823
          goto mandos_end;
962
824
        }
963
825
        
965
827
                          (size_t)decrypted_buffer_size - written,
966
828
                          stdout);
967
829
        if(ret == 0 and ferror(stdout)){
968
 
          int e = errno;
969
830
          if(debug){
970
 
            fprintf(stderr, "Mandos plugin mandos-client: "
971
 
                    "Error writing encrypted data: %s\n",
 
831
            fprintf(stderr, "Error writing encrypted data: %s\n",
972
832
                    strerror(errno));
973
833
          }
974
 
          errno = e;
975
834
          goto mandos_end;
976
835
        }
977
836
        written += (size_t)ret;
983
842
  /* Shutdown procedure */
984
843
  
985
844
 mandos_end:
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
 
    }
 
845
  free(decrypted_buffer);
 
846
  free(buffer);
 
847
  if(tcp_sd >= 0){
 
848
    ret = (int)TEMP_FAILURE_RETRY(close(tcp_sd));
 
849
  }
 
850
  if(ret == -1){
 
851
    perror("close");
 
852
  }
 
853
  gnutls_deinit(session);
 
854
  if(quit_now){
 
855
    retval = -1;
1005
856
  }
1006
857
  return retval;
1007
858
}
1032
883
  switch(event){
1033
884
  default:
1034
885
  case AVAHI_RESOLVER_FAILURE:
1035
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1036
 
            "(Avahi Resolver) Failed to resolve service '%s'"
 
886
    fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'"
1037
887
            " of type '%s' in domain '%s': %s\n", name, type, domain,
1038
888
            avahi_strerror(avahi_server_errno(mc.server)));
1039
889
    break;
1043
893
      char ip[AVAHI_ADDRESS_STR_MAX];
1044
894
      avahi_address_snprint(ip, sizeof(ip), address);
1045
895
      if(debug){
1046
 
        fprintf(stderr, "Mandos plugin mandos-client: "
1047
 
                "Mandos server \"%s\" found on %s (%s, %"
 
896
        fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %"
1048
897
                PRIdMAX ") on port %" PRIu16 "\n", name, host_name,
1049
898
                ip, (intmax_t)interface, port);
1050
899
      }
1052
901
                                           avahi_proto_to_af(proto));
1053
902
      if(ret == 0){
1054
903
        avahi_simple_poll_quit(mc.simple_poll);
1055
 
      } else {
1056
 
        ret = add_server(ip, port, interface,
1057
 
                         avahi_proto_to_af(proto));
1058
904
      }
1059
905
    }
1060
906
  }
1084
930
  default:
1085
931
  case AVAHI_BROWSER_FAILURE:
1086
932
    
1087
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1088
 
            "(Avahi browser) %s\n",
 
933
    fprintf(stderr, "(Avahi browser) %s\n",
1089
934
            avahi_strerror(avahi_server_errno(mc.server)));
1090
935
    avahi_simple_poll_quit(mc.simple_poll);
1091
936
    return;
1099
944
    if(avahi_s_service_resolver_new(mc.server, interface, protocol,
1100
945
                                    name, type, domain, protocol, 0,
1101
946
                                    resolve_callback, NULL) == NULL)
1102
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1103
 
              "Avahi: Failed to resolve service '%s': %s\n",
 
947
      fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n",
1104
948
              name, avahi_strerror(avahi_server_errno(mc.server)));
1105
949
    break;
1106
950
    
1110
954
  case AVAHI_BROWSER_ALL_FOR_NOW:
1111
955
  case AVAHI_BROWSER_CACHE_EXHAUSTED:
1112
956
    if(debug){
1113
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1114
 
              "No Mandos server found, still searching...\n");
 
957
      fprintf(stderr, "No Mandos server found, still searching...\n");
1115
958
    }
1116
959
    break;
1117
960
  }
1118
961
}
1119
962
 
1120
 
/* Signal handler that stops main loop after SIGTERM */
 
963
/* stop main loop after sigterm has been called */
1121
964
static void handle_sigterm(int sig){
1122
965
  if(quit_now){
1123
966
    return;
1125
968
  quit_now = 1;
1126
969
  signal_received = sig;
1127
970
  int old_errno = errno;
1128
 
  /* set main loop to exit */
1129
971
  if(mc.simple_poll != NULL){
1130
972
    avahi_simple_poll_quit(mc.simple_poll);
1131
973
  }
1132
974
  errno = old_errno;
1133
975
}
1134
976
 
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
 
 
1413
977
int main(int argc, char *argv[]){
1414
978
  AvahiSServiceBrowser *sb = NULL;
1415
979
  int error;
1417
981
  intmax_t tmpmax;
1418
982
  char *tmp;
1419
983
  int exitcode = EXIT_SUCCESS;
1420
 
  const char *interface = "";
 
984
  const char *interface = "eth0";
1421
985
  struct ifreq network;
1422
986
  int sd = -1;
1423
987
  bool take_down_interface = false;
1424
988
  uid_t uid;
1425
989
  gid_t gid;
 
990
  char *connect_to = NULL;
1426
991
  char tempdir[] = "/tmp/mandosXXXXXX";
1427
992
  bool tempdir_created = false;
1428
993
  AvahiIfIndex if_index = AVAHI_IF_UNSPEC;
1432
997
  bool gnutls_initialized = false;
1433
998
  bool gpgme_initialized = false;
1434
999
  float delay = 2.5f;
1435
 
  double retry_interval = 10; /* 10s between trying a server and
1436
 
                                 retrying the same server again */
1437
1000
  
1438
1001
  struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL };
1439
1002
  struct sigaction sigterm_action = { .sa_handler = handle_sigterm };
1445
1008
  errno = 0;
1446
1009
  ret = setgid(gid);
1447
1010
  if(ret == -1){
1448
 
    perror_plus("setgid");
 
1011
    perror("setgid");
1449
1012
  }
1450
1013
  
1451
1014
  /* Lower user privileges (temporarily) */
1452
1015
  errno = 0;
1453
1016
  ret = seteuid(uid);
1454
1017
  if(ret == -1){
1455
 
    perror_plus("seteuid");
 
1018
    perror("seteuid");
1456
1019
  }
1457
1020
  
1458
1021
  if(quit_now){
1493
1056
        .arg = "SECONDS",
1494
1057
        .doc = "Maximum delay to wait for interface startup",
1495
1058
        .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 },
1513
1059
      { .name = NULL }
1514
1060
    };
1515
1061
    
1516
1062
    error_t parse_opt(int key, char *arg,
1517
1063
                      struct argp_state *state){
1518
 
      errno = 0;
1519
1064
      switch(key){
1520
1065
      case 128:                 /* --debug */
1521
1066
        debug = true;
1537
1082
        tmpmax = strtoimax(arg, &tmp, 10);
1538
1083
        if(errno != 0 or tmp == arg or *tmp != '\0'
1539
1084
           or tmpmax != (typeof(mc.dh_bits))tmpmax){
1540
 
          argp_error(state, "Bad number of DH bits");
 
1085
          fprintf(stderr, "Bad number of DH bits\n");
 
1086
          exit(EXIT_FAILURE);
1541
1087
        }
1542
1088
        mc.dh_bits = (typeof(mc.dh_bits))tmpmax;
1543
1089
        break;
1548
1094
        errno = 0;
1549
1095
        delay = strtof(arg, &tmp);
1550
1096
        if(errno != 0 or tmp == arg or *tmp != '\0'){
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);
 
1097
          fprintf(stderr, "Bad delay\n");
 
1098
          exit(EXIT_FAILURE);
 
1099
        }
 
1100
        break;
 
1101
      case ARGP_KEY_ARG:
 
1102
        argp_usage(state);
 
1103
      case ARGP_KEY_END:
1579
1104
        break;
1580
1105
      default:
1581
1106
        return ARGP_ERR_UNKNOWN;
1582
1107
      }
1583
 
      return errno;
 
1108
      return 0;
1584
1109
    }
1585
1110
    
1586
1111
    struct argp argp = { .options = options, .parser = parse_opt,
1587
1112
                         .args_doc = "",
1588
1113
                         .doc = "Mandos client -- Get and decrypt"
1589
1114
                         " passwords from a Mandos server" };
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);
 
1115
    ret = argp_parse(&argp, argc, argv, 0, 0, NULL);
 
1116
    if(ret == ARGP_ERR_UNKNOWN){
 
1117
      fprintf(stderr, "Unknown error while parsing arguments\n");
 
1118
      exitcode = EXIT_FAILURE;
 
1119
      goto end;
1758
1120
    }
1759
1121
  }
1760
1122
  
1762
1124
    avahi_set_log_function(empty_log);
1763
1125
  }
1764
1126
  
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
 
  
1799
1127
  /* Initialize Avahi early so avahi_simple_poll_quit() can be called
1800
1128
     from the signal handler */
1801
1129
  /* Initialize the pseudo-RNG for Avahi */
1802
1130
  srand((unsigned int) time(NULL));
1803
1131
  mc.simple_poll = avahi_simple_poll_new();
1804
1132
  if(mc.simple_poll == NULL){
1805
 
    fprintf(stderr, "Mandos plugin mandos-client: "
1806
 
            "Avahi: Failed to create simple poll object.\n");
1807
 
    exitcode = EX_UNAVAILABLE;
 
1133
    fprintf(stderr, "Avahi: Failed to create simple poll object.\n");
 
1134
    exitcode = EXIT_FAILURE;
1808
1135
    goto end;
1809
1136
  }
1810
1137
  
1811
1138
  sigemptyset(&sigterm_action.sa_mask);
1812
1139
  ret = sigaddset(&sigterm_action.sa_mask, SIGINT);
1813
1140
  if(ret == -1){
1814
 
    perror_plus("sigaddset");
1815
 
    exitcode = EX_OSERR;
 
1141
    perror("sigaddset");
 
1142
    exitcode = EXIT_FAILURE;
1816
1143
    goto end;
1817
1144
  }
1818
1145
  ret = sigaddset(&sigterm_action.sa_mask, SIGHUP);
1819
1146
  if(ret == -1){
1820
 
    perror_plus("sigaddset");
1821
 
    exitcode = EX_OSERR;
 
1147
    perror("sigaddset");
 
1148
    exitcode = EXIT_FAILURE;
1822
1149
    goto end;
1823
1150
  }
1824
1151
  ret = sigaddset(&sigterm_action.sa_mask, SIGTERM);
1825
1152
  if(ret == -1){
1826
 
    perror_plus("sigaddset");
1827
 
    exitcode = EX_OSERR;
 
1153
    perror("sigaddset");
 
1154
    exitcode = EXIT_FAILURE;
1828
1155
    goto end;
1829
1156
  }
1830
1157
  /* Need to check if the handler is SIG_IGN before handling:
1833
1160
  */
1834
1161
  ret = sigaction(SIGINT, NULL, &old_sigterm_action);
1835
1162
  if(ret == -1){
1836
 
    perror_plus("sigaction");
1837
 
    return EX_OSERR;
 
1163
    perror("sigaction");
 
1164
    return EXIT_FAILURE;
1838
1165
  }
1839
1166
  if(old_sigterm_action.sa_handler != SIG_IGN){
1840
1167
    ret = sigaction(SIGINT, &sigterm_action, NULL);
1841
1168
    if(ret == -1){
1842
 
      perror_plus("sigaction");
1843
 
      exitcode = EX_OSERR;
 
1169
      perror("sigaction");
 
1170
      exitcode = EXIT_FAILURE;
1844
1171
      goto end;
1845
1172
    }
1846
1173
  }
1847
1174
  ret = sigaction(SIGHUP, NULL, &old_sigterm_action);
1848
1175
  if(ret == -1){
1849
 
    perror_plus("sigaction");
1850
 
    return EX_OSERR;
 
1176
    perror("sigaction");
 
1177
    return EXIT_FAILURE;
1851
1178
  }
1852
1179
  if(old_sigterm_action.sa_handler != SIG_IGN){
1853
1180
    ret = sigaction(SIGHUP, &sigterm_action, NULL);
1854
1181
    if(ret == -1){
1855
 
      perror_plus("sigaction");
1856
 
      exitcode = EX_OSERR;
 
1182
      perror("sigaction");
 
1183
      exitcode = EXIT_FAILURE;
1857
1184
      goto end;
1858
1185
    }
1859
1186
  }
1860
1187
  ret = sigaction(SIGTERM, NULL, &old_sigterm_action);
1861
1188
  if(ret == -1){
1862
 
    perror_plus("sigaction");
1863
 
    return EX_OSERR;
 
1189
    perror("sigaction");
 
1190
    return EXIT_FAILURE;
1864
1191
  }
1865
1192
  if(old_sigterm_action.sa_handler != SIG_IGN){
1866
1193
    ret = sigaction(SIGTERM, &sigterm_action, NULL);
1867
1194
    if(ret == -1){
1868
 
      perror_plus("sigaction");
1869
 
      exitcode = EX_OSERR;
 
1195
      perror("sigaction");
 
1196
      exitcode = EXIT_FAILURE;
1870
1197
      goto end;
1871
1198
    }
1872
1199
  }
1873
1200
  
1874
1201
  /* If the interface is down, bring it up */
1875
 
  if(strcmp(interface, "none") != 0){
 
1202
  if(interface[0] != '\0'){
1876
1203
    if_index = (AvahiIfIndex) if_nametoindex(interface);
1877
1204
    if(if_index == 0){
1878
 
      fprintf(stderr, "Mandos plugin mandos-client: "
1879
 
              "No such interface: \"%s\"\n", interface);
1880
 
      exitcode = EX_UNAVAILABLE;
 
1205
      fprintf(stderr, "No such interface: \"%s\"\n", interface);
 
1206
      exitcode = EXIT_FAILURE;
1881
1207
      goto end;
1882
1208
    }
1883
1209
    
1889
1215
    errno = 0;
1890
1216
    ret = seteuid(0);
1891
1217
    if(ret == -1){
1892
 
      perror_plus("seteuid");
 
1218
      perror("seteuid");
1893
1219
    }
1894
1220
    
1895
1221
#ifdef __linux__
1896
1222
    /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO
1897
 
       messages about the network interface to mess up the prompt */
 
1223
       messages to mess up the prompt */
1898
1224
    ret = klogctl(8, NULL, 5);
1899
1225
    bool restore_loglevel = true;
1900
1226
    if(ret == -1){
1901
1227
      restore_loglevel = false;
1902
 
      perror_plus("klogctl");
 
1228
      perror("klogctl");
1903
1229
    }
1904
1230
#endif  /* __linux__ */
1905
1231
    
1906
1232
    sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP);
1907
1233
    if(sd < 0){
1908
 
      perror_plus("socket");
1909
 
      exitcode = EX_OSERR;
 
1234
      perror("socket");
 
1235
      exitcode = EXIT_FAILURE;
1910
1236
#ifdef __linux__
1911
1237
      if(restore_loglevel){
1912
1238
        ret = klogctl(7, NULL, 0);
1913
1239
        if(ret == -1){
1914
 
          perror_plus("klogctl");
 
1240
          perror("klogctl");
1915
1241
        }
1916
1242
      }
1917
1243
#endif  /* __linux__ */
1919
1245
      errno = 0;
1920
1246
      ret = seteuid(uid);
1921
1247
      if(ret == -1){
1922
 
        perror_plus("seteuid");
 
1248
        perror("seteuid");
1923
1249
      }
1924
1250
      goto end;
1925
1251
    }
1926
1252
    strcpy(network.ifr_name, interface);
1927
1253
    ret = ioctl(sd, SIOCGIFFLAGS, &network);
1928
1254
    if(ret == -1){
1929
 
      perror_plus("ioctl SIOCGIFFLAGS");
 
1255
      perror("ioctl SIOCGIFFLAGS");
1930
1256
#ifdef __linux__
1931
1257
      if(restore_loglevel){
1932
1258
        ret = klogctl(7, NULL, 0);
1933
1259
        if(ret == -1){
1934
 
          perror_plus("klogctl");
 
1260
          perror("klogctl");
1935
1261
        }
1936
1262
      }
1937
1263
#endif  /* __linux__ */
1938
 
      exitcode = EX_OSERR;
 
1264
      exitcode = EXIT_FAILURE;
1939
1265
      /* Lower privileges */
1940
1266
      errno = 0;
1941
1267
      ret = seteuid(uid);
1942
1268
      if(ret == -1){
1943
 
        perror_plus("seteuid");
 
1269
        perror("seteuid");
1944
1270
      }
1945
1271
      goto end;
1946
1272
    }
1950
1276
      ret = ioctl(sd, SIOCSIFFLAGS, &network);
1951
1277
      if(ret == -1){
1952
1278
        take_down_interface = false;
1953
 
        perror_plus("ioctl SIOCSIFFLAGS +IFF_UP");
1954
 
        exitcode = EX_OSERR;
 
1279
        perror("ioctl SIOCSIFFLAGS");
 
1280
        exitcode = EXIT_FAILURE;
1955
1281
#ifdef __linux__
1956
1282
        if(restore_loglevel){
1957
1283
          ret = klogctl(7, NULL, 0);
1958
1284
          if(ret == -1){
1959
 
            perror_plus("klogctl");
 
1285
            perror("klogctl");
1960
1286
          }
1961
1287
        }
1962
1288
#endif  /* __linux__ */
1964
1290
        errno = 0;
1965
1291
        ret = seteuid(uid);
1966
1292
        if(ret == -1){
1967
 
          perror_plus("seteuid");
 
1293
          perror("seteuid");
1968
1294
        }
1969
1295
        goto end;
1970
1296
      }
1971
1297
    }
1972
 
    /* Sleep checking until interface is running.
1973
 
       Check every 0.25s, up to total time of delay */
 
1298
    /* sleep checking until interface is running */
1974
1299
    for(int i=0; i < delay * 4; i++){
1975
1300
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
1976
1301
      if(ret == -1){
1977
 
        perror_plus("ioctl SIOCGIFFLAGS");
 
1302
        perror("ioctl SIOCGIFFLAGS");
1978
1303
      } else if(network.ifr_flags & IFF_RUNNING){
1979
1304
        break;
1980
1305
      }
1981
1306
      struct timespec sleeptime = { .tv_nsec = 250000000 };
1982
1307
      ret = nanosleep(&sleeptime, NULL);
1983
1308
      if(ret == -1 and errno != EINTR){
1984
 
        perror_plus("nanosleep");
 
1309
        perror("nanosleep");
1985
1310
      }
1986
1311
    }
1987
1312
    if(not take_down_interface){
1988
1313
      /* We won't need the socket anymore */
1989
1314
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
1990
1315
      if(ret == -1){
1991
 
        perror_plus("close");
 
1316
        perror("close");
1992
1317
      }
1993
1318
    }
1994
1319
#ifdef __linux__
1996
1321
      /* Restores kernel loglevel to default */
1997
1322
      ret = klogctl(7, NULL, 0);
1998
1323
      if(ret == -1){
1999
 
        perror_plus("klogctl");
 
1324
        perror("klogctl");
2000
1325
      }
2001
1326
    }
2002
1327
#endif  /* __linux__ */
2006
1331
      /* Lower privileges */
2007
1332
      ret = seteuid(uid);
2008
1333
      if(ret == -1){
2009
 
        perror_plus("seteuid");
 
1334
        perror("seteuid");
2010
1335
      }
2011
1336
    } else {
2012
1337
      /* Lower privileges permanently */
2013
1338
      ret = setuid(uid);
2014
1339
      if(ret == -1){
2015
 
        perror_plus("setuid");
 
1340
        perror("setuid");
2016
1341
      }
2017
1342
    }
2018
1343
  }
2023
1348
  
2024
1349
  ret = init_gnutls_global(pubkey, seckey);
2025
1350
  if(ret == -1){
2026
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2027
 
            "init_gnutls_global failed\n");
2028
 
    exitcode = EX_UNAVAILABLE;
 
1351
    fprintf(stderr, "init_gnutls_global failed\n");
 
1352
    exitcode = EXIT_FAILURE;
2029
1353
    goto end;
2030
1354
  } else {
2031
1355
    gnutls_initialized = true;
2035
1359
    goto end;
2036
1360
  }
2037
1361
  
 
1362
  tempdir_created = true;
2038
1363
  if(mkdtemp(tempdir) == NULL){
2039
 
    perror_plus("mkdtemp");
 
1364
    tempdir_created = false;
 
1365
    perror("mkdtemp");
2040
1366
    goto end;
2041
1367
  }
2042
 
  tempdir_created = true;
2043
1368
  
2044
1369
  if(quit_now){
2045
1370
    goto end;
2046
1371
  }
2047
1372
  
2048
1373
  if(not init_gpgme(pubkey, seckey, tempdir)){
2049
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2050
 
            "init_gpgme failed\n");
2051
 
    exitcode = EX_UNAVAILABLE;
 
1374
    fprintf(stderr, "init_gpgme failed\n");
 
1375
    exitcode = EXIT_FAILURE;
2052
1376
    goto end;
2053
1377
  } else {
2054
1378
    gpgme_initialized = true;
2063
1387
    /* (Mainly meant for debugging) */
2064
1388
    char *address = strrchr(connect_to, ':');
2065
1389
    if(address == NULL){
2066
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2067
 
              "No colon in address\n");
2068
 
      exitcode = EX_USAGE;
 
1390
      fprintf(stderr, "No colon in address\n");
 
1391
      exitcode = EXIT_FAILURE;
2069
1392
      goto end;
2070
1393
    }
2071
1394
    
2078
1401
    tmpmax = strtoimax(address+1, &tmp, 10);
2079
1402
    if(errno != 0 or tmp == address+1 or *tmp != '\0'
2080
1403
       or tmpmax != (uint16_t)tmpmax){
2081
 
      fprintf(stderr, "Mandos plugin mandos-client: "
2082
 
              "Bad port number\n");
2083
 
      exitcode = EX_USAGE;
 
1404
      fprintf(stderr, "Bad port number\n");
 
1405
      exitcode = EXIT_FAILURE;
2084
1406
      goto end;
2085
1407
    }
2086
1408
  
2090
1412
    
2091
1413
    port = (uint16_t)tmpmax;
2092
1414
    *address = '\0';
 
1415
    address = connect_to;
2093
1416
    /* Colon in address indicates IPv6 */
2094
1417
    int af;
2095
 
    if(strchr(connect_to, ':') != NULL){
 
1418
    if(strchr(address, ':') != NULL){
2096
1419
      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
 
        }
2103
1420
    } else {
2104
1421
      af = AF_INET;
2105
1422
    }
2106
 
    address = connect_to;
2107
1423
    
2108
1424
    if(quit_now){
2109
1425
      goto end;
2110
1426
    }
2111
1427
    
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){
 
1428
    ret = start_mandos_communication(address, port, if_index, af);
 
1429
    if(ret < 0){
 
1430
      exitcode = EXIT_FAILURE;
 
1431
    } else {
2125
1432
      exitcode = EXIT_SUCCESS;
2126
1433
    }
2127
 
    
2128
1434
    goto end;
2129
1435
  }
2130
1436
  
2152
1458
  
2153
1459
  /* Check if creating the Avahi server object succeeded */
2154
1460
  if(mc.server == NULL){
2155
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2156
 
            "Failed to create Avahi server: %s\n",
 
1461
    fprintf(stderr, "Failed to create Avahi server: %s\n",
2157
1462
            avahi_strerror(error));
2158
 
    exitcode = EX_UNAVAILABLE;
 
1463
    exitcode = EXIT_FAILURE;
2159
1464
    goto end;
2160
1465
  }
2161
1466
  
2168
1473
                                   AVAHI_PROTO_UNSPEC, "_mandos._tcp",
2169
1474
                                   NULL, 0, browse_callback, NULL);
2170
1475
  if(sb == NULL){
2171
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2172
 
            "Failed to create service browser: %s\n",
 
1476
    fprintf(stderr, "Failed to create service browser: %s\n",
2173
1477
            avahi_strerror(avahi_server_errno(mc.server)));
2174
 
    exitcode = EX_UNAVAILABLE;
 
1478
    exitcode = EXIT_FAILURE;
2175
1479
    goto end;
2176
1480
  }
2177
1481
  
2182
1486
  /* Run the main loop */
2183
1487
  
2184
1488
  if(debug){
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
 
  }
 
1489
    fprintf(stderr, "Starting Avahi loop search\n");
 
1490
  }
 
1491
  
 
1492
  avahi_simple_poll_loop(mc.simple_poll);
2196
1493
  
2197
1494
 end:
2198
1495
  
2199
1496
  if(debug){
2200
 
    fprintf(stderr, "Mandos plugin mandos-client: "
2201
 
            "%s exiting\n", argv[0]);
 
1497
    fprintf(stderr, "%s exiting\n", argv[0]);
2202
1498
  }
2203
1499
  
2204
1500
  /* Cleanup things */
2220
1516
  if(gpgme_initialized){
2221
1517
    gpgme_release(mc.ctx);
2222
1518
  }
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  */
2236
1519
  
2237
1520
  /* Take down the network interface */
2238
1521
  if(take_down_interface){
2240
1523
    errno = 0;
2241
1524
    ret = seteuid(0);
2242
1525
    if(ret == -1){
2243
 
      perror_plus("seteuid");
 
1526
      perror("seteuid");
2244
1527
    }
2245
1528
    if(geteuid() == 0){
2246
1529
      ret = ioctl(sd, SIOCGIFFLAGS, &network);
2247
1530
      if(ret == -1){
2248
 
        perror_plus("ioctl SIOCGIFFLAGS");
2249
 
      } else if(network.ifr_flags & IFF_UP){
2250
 
        network.ifr_flags &= ~(short)IFF_UP; /* clear flag */
 
1531
        perror("ioctl SIOCGIFFLAGS");
 
1532
      } else if(network.ifr_flags & IFF_UP) {
 
1533
        network.ifr_flags &= ~IFF_UP; /* clear flag */
2251
1534
        ret = ioctl(sd, SIOCSIFFLAGS, &network);
2252
1535
        if(ret == -1){
2253
 
          perror_plus("ioctl SIOCSIFFLAGS -IFF_UP");
 
1536
          perror("ioctl SIOCSIFFLAGS");
2254
1537
        }
2255
1538
      }
2256
1539
      ret = (int)TEMP_FAILURE_RETRY(close(sd));
2257
1540
      if(ret == -1){
2258
 
        perror_plus("close");
 
1541
        perror("close");
2259
1542
      }
2260
1543
      /* Lower privileges permanently */
2261
1544
      errno = 0;
2262
1545
      ret = setuid(uid);
2263
1546
      if(ret == -1){
2264
 
        perror_plus("setuid");
 
1547
        perror("setuid");
2265
1548
      }
2266
1549
    }
2267
1550
  }
2268
1551
  
2269
 
  /* Removes the GPGME temp directory and all files inside */
 
1552
  /* Removes the temp directory used by GPGME */
2270
1553
  if(tempdir_created){
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];
 
1554
    DIR *d;
 
1555
    struct dirent *direntry;
 
1556
    d = opendir(tempdir);
 
1557
    if(d == NULL){
 
1558
      if(errno != ENOENT){
 
1559
        perror("opendir");
 
1560
      }
 
1561
    } else {
 
1562
      while(true){
 
1563
        direntry = readdir(d);
 
1564
        if(direntry == NULL){
 
1565
          break;
 
1566
        }
 
1567
        /* Skip "." and ".." */
 
1568
        if(direntry->d_name[0] == '.'
 
1569
           and (direntry->d_name[1] == '\0'
 
1570
                or (direntry->d_name[1] == '.'
 
1571
                    and direntry->d_name[2] == '\0'))){
 
1572
          continue;
 
1573
        }
2278
1574
        char *fullname = NULL;
2279
1575
        ret = asprintf(&fullname, "%s/%s", tempdir,
2280
1576
                       direntry->d_name);
2281
1577
        if(ret < 0){
2282
 
          perror_plus("asprintf");
 
1578
          perror("asprintf");
2283
1579
          continue;
2284
1580
        }
2285
1581
        ret = remove(fullname);
2286
1582
        if(ret == -1){
2287
 
          fprintf(stderr, "Mandos plugin mandos-client: "
2288
 
                  "remove(\"%s\"): %s\n", fullname, strerror(errno));
 
1583
          fprintf(stderr, "remove(\"%s\"): %s\n", fullname,
 
1584
                  strerror(errno));
2289
1585
        }
2290
1586
        free(fullname);
2291
1587
      }
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");
 
1588
      closedir(d);
2298
1589
    }
2299
1590
    ret = rmdir(tempdir);
2300
1591
    if(ret == -1 and errno != ENOENT){
2301
 
      perror_plus("rmdir");
 
1592
      perror("rmdir");
2302
1593
    }
2303
1594
  }
2304
1595
  
2309
1600
                                            &old_sigterm_action,
2310
1601
                                            NULL));
2311
1602
    if(ret == -1){
2312
 
      perror_plus("sigaction");
 
1603
      perror("sigaction");
2313
1604
    }
2314
1605
    do {
2315
1606
      ret = raise(signal_received);
2316
1607
    } while(ret != 0 and errno == EINTR);
2317
1608
    if(ret != 0){
2318
 
      perror_plus("raise");
 
1609
      perror("raise");
2319
1610
      abort();
2320
1611
    }
2321
1612
    TEMP_FAILURE_RETRY(pause());